which is more 'pythonic' / 'better' ?

Peter Hansen peter at engcorp.com
Tue Sep 13 23:48:27 CEST 2005


Ken Seehart wrote:
> Will McGugan wrote:
>> I would actualy use the following for this particular case..
>>
>> text = line[n:n+1] or 'nothing'

> Hey are you a perl programmer?  That looks perlish to me.  A python 
> programmer would never use "or" that way (even though it works).  :)

I don't think that's at all true.  The pattern "somevalue or default" is 
an accepted idiom for returning a default value when "somevalue" is 
False, often used inside __init__ methods to set up attributes.  A most 
common case is like this (inside a class obviously):

def meth(self, things=None):
     self.things = things or []

(The reason you don't just use a keyword argument of "things=[]" should 
be obvious to all but newbies, and they'll learn a lot by researching 
why so I won't say here. ;-)  )

The alternative is fine too, but insisting on it would be pedantic, and 
if you have more than one of these it is definitely less readable (and, 
therefore, not Pythonic):

def meth(self, things=None):
     if things:
         self.things = things
     else:
         self.things = []

> It's okay, I used to be a perl programmer too.  It's nothing to be 
> ashamed of. :)

Ah, now I would disagree with that as well! ;-)

-Peter



More information about the Python-list mailing list