question about True values

George Sakkis george.sakkis at gmail.com
Wed Oct 25 18:28:25 EDT 2006


Martin v. Löwis wrote:

> skip at pobox.com schrieb:
> > the string class's "nil" value.  Each of the builtin types has such an
> > "empty" or "nil" value:
> >
> >     string              ""
> >     list                []
> >     tuple               ()
> >     dict                {}
> >     int                 0
> >     float               0.0
> >     complex             0j
> >     set                 set()
> >
> > Any other value besides the above will compare as "not false".
>
> This list of values that are considered false is incomplete,
> though. Four obvious omissions are
>
> long       0L
> unicode    u""
> bool       False
> NoneType   None
>
> Not-so-obviously, arbitrary user-defined values can also be
> treated as false: If they implement __nonzero__, they are
> false if False is returned from __nonzero__; otherwise,
> if they implement __len__, they are false if 0 is returned
> from __len__. Under these rules, array.array objects can
> also be false, as can UserList and UserDict objects.

A notable exception are numarray arrays (probably true for numpy too, I
haven't tested it though):

>>> from numarray import array
>>> bool(array([1,2]))
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
RuntimeError: An array doesn't make sense as a truth value.  Use any(a)
or all(a).

George




More information about the Python-list mailing list