which is more 'pythonic' / 'better' ?

Ken Seehart pythonic at seehart.com
Tue Sep 13 17:08:27 EDT 2005


Will McGugan wrote:
> gabor wrote:
> 
>> hi,
>>
>> there are 2 versions of a simple code.
>> which is preferred?
>>
>>
>> ===
>> if len(line) >= (n+1):
>>     text = line[n]
>> else:
>>     text = 'nothing'
>> ===
>>
>>
>> ===
>> try:
>>     text = line[n]
>> except IndexError:
>>     text = 'nothing'
>> ===
>>
>>
>> which is the one you would use?
> 
> 
> I would actualy use the following for this particular case..
> 
> text = line[n:n+1] or 'nothing'
> 
> But in general I think it is best to use exceptions like that only where 
>  you expect the code to _not_ throw the exception the majority of times. 
> Otherwise the simple condition is better. Although I expect there is not 
> much difference either way..
> 
> 
> Will McGugan
> -- 
> http://www.kelpiesoft.com

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

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

- Ken




More information about the Python-list mailing list