When a Python tuple is used in a boolean context, it is considered True
if and only if it is not empty.
Does the same apply to instances of collections.namedtuple
?
When a Python tuple is used in a boolean context, it is considered True
if and only if it is not empty.
Does the same apply to instances of collections.namedtuple
?
Yes, but in general you probably won't ever see it happen, since you specify names for each value in the namedtuple
. Specifying no names would allow you to create an empty tuple type, but such a type would not be very useful, since its instances will always be empty:
>>> empty = collections.namedtuple("empty", [])
>>> empty()
empty()
>>> bool(empty())
False
Yes. You can see this by inspecting a named tuple class.
One way to do so is to view a named tuple class's source code, using ._source
in Python 3.3 or later, or the verbose=True
option to namedtuple()
. You will see that named tuples extend tuple
, and don't override the __nonzero__()
or __len__()
methods. This means they use the same logic as tuple
, like you thought.
You can also check a named tuple class's __nonzero__
and __len__
attributes. You will see that it has no __nonzero__
attribute defined, and that the __len__
attribute is the same as the one for tuple
:
>>> A = namedtuple('A', ['x'])
>>> A.__len__ == tuple.__len__
True
In theory, yes, but you can't create an empty instance of any useful namedtuple, because when you create a namedtuple type, you have to specify the number of elements up front. So the only way you can have an empty namedtuple is to have a namedtuple type that is always empty, in which case it serves no purpose.