I have subclassed the builtin Python list.
An empty list will evaluate to false in an if construct, but I want my subclass to evaluate to true.
Is there any dunder method available that I can override in my subclass to change this behavior?
I have subclassed the builtin Python list.
An empty list will evaluate to false in an if construct, but I want my subclass to evaluate to true.
Is there any dunder method available that I can override in my subclass to change this behavior?
According to the Python datamodel documentation, for the object.__nonzero__
method, this is doable (but it would violate the rule of least surprise, or principle of least astonishment):
Called to implement truth value testing and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, len() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither len() nor nonzero(), all its instances are considered true.
Therefore hypothetically, we can check for len() == 0 and return True if it is, and then use the default for the boolean check:
class FunkyList(list):
def __nonzero__(self):
if self.__len__() == 0:
return True
else:
return self.__len__()
__bool__ = __nonzero__ # Python 3 uses __bool__ instead of __nonzero
But since both cases of the logic tree result in a bool of True, the above can be simplified to:
class FunkyList(list):
def __nonzero__(self):
return True
__bool__ = __nonzero__ # Python 3 uses __bool__ instead of __nonzero
And we see it works and looks like a list:
>>> fl = FunkyList()
>>> fl
[]
>>> isinstance(fl, list)
True
And now bool() of the empty FunkyList returns True
>>> bool(fl)
True
And it does that without hacking the __len__
method.
>>> len(fl)
0
Regardless, I don't understand why you would want a list of len 0 to return True.
Thanks for such an interesting question, but I hope the matter is academic, and not practical. It's idiomatic of Python to do this check:
>>> if fl:
... print True
...
True
And anyone experienced in Python would expect that to return False if the list is empty, and the results of implementing this would probably make any user quite unhappy with you.
i don't know whether it helpful for you but i tried this.... list_1= [["a","b"]] where ''list_1' is list name and '["a","b"]' is subset of list. if you execute following code
list_1 = [["a","b"]];
if "a" in list_1:
print ("true");
else:
print ("false");
will gives you "false" .....
if you execute this code
list_1 = [["a","b"]];
if "a" in list_1[0]:
print ("true");
else:
print ("false");
it will gives you "true"
by this way you can access sublist in list...