<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def collapse_nested(self, cats, max_nestedness=10):
 """ Collapse any items that are nested under cats. `max_nestedness` acts as a fail-safe to prevent infinite looping. """

        children = []
        removed = set()
        nestedness = max_nestedness

        old = list(self.widget.options.values())
        nested = [cat for cat in old if getattr(cat, 'cat') is not None]
        parents = {cat.cat for cat in nested}
        parents_to_remove = cats
        while len(parents_to_remove) > 0 and nestedness > 0:
            for cat in nested:
                if cat.cat in parents_to_remove:
                    children.append(cat)
            removed = removed.union(parents_to_remove)
            nested = [cat for cat in nested if cat not in children]
            parents_to_remove = {c for c in children if c in parents - removed}
            nestedness -= 1
        self.remove(children)