I have read overriding bool() for custom class and it doesn't answer my question, "how to implement a list subclass that evaluates as False if its items evaluate as False". Specifically, it doesn't address:
- subclassing a list
- evaluating as False in a boolean context if its items evaluate as False in a boolean context
Motivation
One might have a data-model requires deeply nested lists of lists, and one might require an easier solution than recursing through the list of lists to determine if it has accumulated something that evaluates as True in a boolean context.
The Context
In Python an empty list evaluates as False
>>> l = list()
>>> l
[]
>>> bool(l)
False
But a list with an empty list, (or some other 0 or empty container) in it evaluates as True
because the len of the containing list is > 0.
>>> l.append([])
>>> l
[[]]
>>> bool(l)
True
Question:
Can I subclass a list such that it is an instance of a list but that if it contains empty lists or other things that evaluate as empty or False
will return False
?
i.e.:
>>> l = MagicList((None, 0, {}, MagicList([0, False])))
>>> isinstance(l, list)
True
>>> bool(l)
False