| Store | Cart

Python style guidelines

From: Peter Otten <__pe...@web.de>
Thu, 11 Mar 2004 12:18:01 +0100
Josef Meile wrote:

>> Is there something missing you think should be there?  There's no>> particular>> reason a PEP needs to be continually updated.  In particular, notions of>> good Python style haven't changed a lot over the past ten years.>> >> Skip> I agree, those are good guidelines, but I don't agree with:> > - Don't compare boolean values to True or False using == (bool>    types are new in Python 2.3):> >          No:  if greeting == True:>          Yes: if greeting:> > What would happened if you do:> >  >>> a='test'>  >>> if a.find('foo'):> ...    print "foo was found"> ...> foo was found> > I think you should never do a direct boolean comparison. Instead> one should use a more elaborate boolean expresion like:> >  >>> a='test'>  >>> if a.find('foo') >= 0:> ...    print "foo was found"> ...> > > You will have problems specially if you come from languages where> values minor than zero are considered to be false. I think the> previous sintax is ambiguous.

I think your find() example has nothing to do with 

if boolVal == True:

versus

if boolVal:

though it might be a pitfall for people coming from languages with 1-based
indices. If you discard the index it returns anyway, you could use the
clearer

if "foo" in a:

instead.

As to the original issue, I disagree with you and prefer the recommended
style. I find it natural even for non-booleans:

greeting = "Hi"
if greeting:
    print greeting

If you expect a boolean value and fear that you may erroneously encounter
something else, the value == True test will not be sufficient anyway,
because treating, say, "Hi" as False may be an error, too. It's

if greeting == True:
   ...
elif greeting == False:
   pass
else:
   raise AssertionError, "greeting must be True or False"

versus

assert greeting in (True, False), "greeting must be True or False"
if greeting:
   ...

then, and again the last wins at in my eyes.

Peter

Recent Messages in this Thread
beli...@aol.com Mar 10, 2004 07:12 pm
Skip Montanaro Mar 10, 2004 10:09 pm
Will Berry Mar 11, 2004 10:39 pm
Richie Hindle Mar 12, 2004 09:36 am
Jorgen Grahn Mar 12, 2004 07:29 pm
MetalOne Mar 13, 2004 07:08 am
Heather Coppersmith Mar 13, 2004 01:22 pm
MetalOne Mar 13, 2004 09:28 pm
Andy Salnikov Mar 15, 2004 09:34 pm
wmwd...@sneakemail.com ) (Greg Ewing (using news.cis.dfn.de) Mar 15, 2004 12:39 am
Josef Meile Mar 11, 2004 09:48 am
Peter Otten Mar 11, 2004 11:18 am
Heather Coppersmith Mar 11, 2004 11:34 am
Josef Meile Mar 11, 2004 03:39 pm
Peter Hansen Mar 11, 2004 03:41 pm
Donn Cave Mar 11, 2004 04:49 pm
John Roth Mar 11, 2004 05:16 pm
wmwd...@sneakemail.com ) (Greg Ewing (using news.cis.dfn.de) Mar 12, 2004 03:23 am
Mel Wilson Mar 12, 2004 03:57 pm
Aahz Mar 11, 2004 04:27 pm
beli...@aol.com Mar 11, 2004 12:52 pm
Michael Hudson Mar 11, 2004 01:41 pm
Messages in this thread

Previous post: embed python
Next post: Video module?