[Python-3000] __nonzero__ vs. __bool__

Jack Diederich jackdied at jackdied.com
Wed Nov 22 18:04:32 CET 2006


On Wed, Nov 22, 2006 at 09:36:09AM +0100, Georg Brandl wrote:
> Terry Reedy schrieb:
> > "Brett Cannon" <brett at python.org> wrote in message 
> > news:bbaeab100611211232r53de3c33p915bee7b49dbdf9a at mail.gmail.com...
> > 
> > Why can't the fallback usage just pass the return value from __len__ to 
> > bool() (forget the C function name) and return that result?  It's just like 
> > doing::
> > 
> >   def bool(obj):
> >       try:
> >           return obj.__bool__()
> >       except AttributeError:
> >           return bool(len(obj))
> > ------------
> > 
> > If an object without __bool__ returned itself as its length, this would be 
> > an infinite loop, at least in this Python version.  Do we worry about 
> > something so crazy?
> 
> The length would have to be an integer, and this would have to be checked.
> 

It looks like the regular checks are happening on __len__ methods
anyway so the explicit int check in slot_nb_bool is redundant.
This is the first time I've looked at the new slots in py3k so
feel free to correct. (using bool4.patch)

sprat:~/src/py3k-rw> ./python
Python 3.0x (p3yk:52823M, Nov 22 2006, 11:57:34) 
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
  def __len__(self):
    return -1

a = A()
print bool(a)
  ... ... ... >>> >>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: __len__() should return >= 0
>>> 

-Jack


More information about the Python-3000 mailing list