[Python-Dev] bool(container) [was bool(iter([])) changed between 2.3 and 2.4]

Guido van Rossum guido at python.org
Fri Sep 30 18:16:39 CEST 2005


On 9/30/05, Jim Jewett <jimjjewett at gmail.com> wrote:
> If I submit a documentation patch, should I say that
> numbers, lists, strings, dictionaries, and tuples are
> a special case, or should I just warn that some
> container-like objects (including iterators) are always
> True?

You seem to be going at this from the wrong direction. Boolean value
are defined by calling __nonzero__ or __len__, whichever exists; if
neither exists the answer is true (except for None which is
special-cased only for historical reasons -- there's no reason why it
couldn't have a __nonzero__ method.

__nonzero__ is intended for object types that either want to have
number-like behavior or have a special reason for wanting to act like
a Boolean.

__len__ is for sequences and mappings specifically -- everything that
supports __getitem__ should have __len__ and everything that has
__len__ should have __getitem__. (This is what broke for iterators in
2.4.)

So if anything's an "exception", it's numbers -- strings, lists,
tuples are sequences and dicts are mappings, and that's where they get
their definition of Booleanness from.

Always remember, user-defined classes can define __nonzero__ any way
they wish, and they get what they deserve. Library designers however
should try to follow established patterns. Testing for Queue emptiness
via __nonzero__ seems unwarranted since a Queue doesn't have any other
sequence behavior.

"Containerish" behavior isn't enough to warrant empty <--> false; in
some sense every object is a container (at least every object with a
__dict__ attribute) and you sure don't want to map __len__ to
self.__dict__.__len__...

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list