[Python-Dev] bool(container) [was bool(iter([])) changed between 2.3 and 2.4] (original) (raw)
Guido van Rossum guido at python.org
Fri Sep 30 18:16:39 CEST 2005
- Previous message: [Python-Dev] bool(container) [was bool(iter([])) changed between 2.3 and 2.4]
- Next message: [Python-Dev] bool(container) [was bool(iter([])) changedbetween 2.3 and 2.4]
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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/)
- Previous message: [Python-Dev] bool(container) [was bool(iter([])) changed between 2.3 and 2.4]
- Next message: [Python-Dev] bool(container) [was bool(iter([])) changedbetween 2.3 and 2.4]
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]