Default __nonzero__ impl doesn't throw a TypeError exception

Chris Rebert clp2 at rebertia.com
Thu Jan 8 15:03:35 EST 2009


On Thu, Jan 8, 2009 at 5:53 AM, Sergey Kishchenko <voidwrk at gmail.com> wrote:
> In Python empty container equals False in 'if' statements:
>
> # prints "It's ok"
> if not []:
>    print "It's ok"
>
> Let's create a simple Foo class:
>
> class Foo:
>    pass
>
> Now I can use Foo objects in 'if' statements:
>
> #prints "Ouch!"
> f=Foo()
> if f:
>    print "Ouch!"
>
> So, default __nonzero__ impl is to return True. I think, this
> behaviour conflicts with 'Explicit is better than implicit' and
> 'Practicality beats purity' statements. I think, throwing a TypeError
> exception would be better.  It will result in more explicit code with
> fewer errors.

Python has a rich notion of boolean truth compared to other languages.
In this case, by default, non-None objects are considered True. It's a
reasonable default behavior since wanting to differentiate between
None and non-None objects is such a common task.
Also, I've been programming in Python for a long while and have yet to
encounter any bug due to this behavior.
Regarding the Zen, on the contrary, this is a perfect example of
"Practicality beats purity" in action.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list