Implicit conversion to boolean in if and while statements

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jul 17 08:25:43 CEST 2012


On Tue, 17 Jul 2012 00:18:28 -0400, Devin Jeanpierre wrote:

> On Mon, Jul 16, 2012 at 12:03 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> On Sun, 15 Jul 2012 22:15:13 -0400, Devin Jeanpierre wrote:
>>
>>> For example, instead of "if stack:" or "if bool(stack):", we could use
>>> "if stack.isempty():". This line tells us explicitly that stack is a
>>> container.
>>
>> isempty is not a container method.
> 
> Your entire reply is predicated on this idea that I was talking about
> writing classes with this extra "isempty" method.
> 
> No. I was talking about having "isempty" be part of the collection
> interface, and eliminating polymorphic bool conversion.

It already is part of the collection interface: it is spelled __nonzero__ 
(Python 2) or __bool__ (Python 3), and like all dunder methods, it is 
called automatically for you when you use the right syntax:

# do this
x = n - len(y)
if x and y:
    ...

# don't do this
x = n.__sub__(y.__len__())
if x.__nonzero__() and y.__nonzero__():
    ...


-- 
Steven



More information about the Python-list mailing list