__len__ and boolean values - small language change

Andrew Cooke andrew at andrewcooke.free-online.co.uk
Mon May 8 12:40:36 EDT 2000


Hi,

"if foo:" seems to check foo.__len__() if implemented.  This makes sense
for built-in sequences, but may not be useful for user-defined classes.
For example, I have a tree of node classes that I would like to be true
or false depending on their contents rather than on the number of
subnodes.  But I also want to use __len__ to give the number of subnodes
because it makes the rest of the code more elegant (ie when nodes
implement the full set of sequence methods, not just __len__ in
isolation).

Is there a special method that I can override to provide boolean values
in tests, or is __len__ called directly?  If the latter, would it be
possible to add a new method (__true__?) that by default calls
self.__len__, but which could be altered if necessary?  This change
would only break code that already had __true__ methods.  If people
don't use the __foo__ style for method names in case of such conflicts
then this seems like a minor change that would damage little and make
the language a little more consistent.

Cheers,
Andrew

http://www.andrewcooke.free-online.co.uk/index.html


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list