[Python-ideas] Programming recommendations (PEP 8) and boolean values

Ronan Lamy ronan.lamy at gmail.com
Wed Aug 8 23:38:28 CEST 2012


Le mercredi 08 août 2012 à 22:29 +0200, Georg Brandl a écrit :
> On 08.08.2012 19:53, Rob Cliffe wrote:
> >
> > On 08/08/2012 17:59, Oleg Broytman wrote:

> > Also I find the advice that
> >       if x is True:
> > is worse than
> >       if x==True:
> > baffling.  I have been taught that the former executes faster, and
> > indeed when I test it I find it is (significantly faster).
> > What is the rationale?
> 
> Because in most cases you want to accept 1 and 0 too for True and False.
> 
> For None, "==" and "is" are equivalent, because no other object is equal
> to None.  For True and False, this is different, and using "is" here is
> a very stealthy bug.

But do you really want to accept 1.0 but reject 1.0001? I would say that
using "x == True" is the stealthier bug:

>>> def do_stuff(n):
...     a = 1; a /= n; a *= n
...     if a == True:
...         return 0
...     else:
...         return "BOOM!"
...     
>>> [do_stuff(n) for n in range(42, 54)]
[0, 0, 0, 0, 0, 0, 0, 'BOOM!', 0, 0, 0, 0]

-- 
Ronan Lamy <ronan.lamy at gmail.com>




More information about the Python-ideas mailing list