Boolean tests [was Re: Attack a sacred Python Cow]
Heiko Wundram
modelnine at modelnine.org
Tue Jul 29 12:36:32 CEST 2008
Am Dienstag, 29. Juli 2008 11:15:05 schrieb Heiko Wundram:
> I can't dig up a simple example from code I wrote quickly...
Just to get back to that: an example I found where "if x" (the generic
__nonzero__() test) will work to test for emptiness/non-emptiness of a
container, whereas "if len(x) > 0" (the "specific" test for this example)
will not, is my for own integer set type I wrote a while back (which you can
find on ASPN).
The corresponding set type allows you to create infinitely sized sets of
integers (which of course are stored as pairs of <start>,<stop>-values, so
the storage itself for the set is bounded), for which len(x) does not have
a "proper" meaning anymore, and __len__() is limited to returning a (platform
dependent) ssize_t anyway IIRC, so even with a bounded set, the length of the
set might not necessarily be accessible using len(x); that's why the set type
additionally got a member function called .len() to work around this
restriction.
I should think is a non-contrieved example where the generic test whether the
object considers itself True/False (which for containers means
non-empty/empty) is preferrable over the special case test whether the length
is positive. A polymorphic function, which for example only accesses the
first ten members of the container is able to work with an infinite set if it
uses the generic test, but is not in case it uses len(x) > 0.
--
Heiko Wundram
More information about the Python-list
mailing list