[BangPypers] ElementTree object instance evaluates to False?
Noufal Ibrahim
noufal at gmail.com
Tue Dec 6 06:45:03 CET 2011
Vikas BN <vikas.bn at gmail.com> writes:
[...]
> Anyone else encountered this or even have any insights regarding
> this behaviour? I'm using Python2.7.2 on Linux
> if that matters.
ElementTree's `Element` objects behave this way. The "booleanness" is
not conformant to the rest of Python.
I don't know if or when it's been fixed but here's how to do it.
http://effbot.org/zone/element.htm#truth-testing
The method you need to work with is `__nonzero__`[1] if you want `bool`
to work with your classes.
With Python 2.7.2, The `Element` class defined in
/usr/lib/python2.7/xml/etree/ElementTree.py has
def __nonzero__(self):
warnings.warn(
"The behavior of this method will change in future versions. "
"Use specific 'len(elem)' or 'elem is not None' test instead.",
FutureWarning, stacklevel=2
)
return len(self._children) != 0 # emulate old behaviour, for now
So, it will evaluate to False only if the number of children is
zero.
Annoying but when I stumbled on this, it did make me aware of how
consistent Python libraries generally are so that this stuck out.
[...]
Footnotes:
[1] http://docs.python.org/reference/datamodel.html#object.__nonzero__
--
~noufal
http://nibrahim.net.in
I am a deeply superficial person. -Andy Warhol
More information about the BangPypers
mailing list