PEP 308: A PEP Writer's Experience - PRO

David Eppstein eppstein at
Mon Feb 10 22:20:21 CET 2003

In article <mailman.1044904883.10775.python-list at>,
 holger krekel <pyth at> wrote:

> People using the ternary-op may easily fail to realize
> that the idiom isn't the right one all the time.  For example,
> it might prevent people from learning about the specific pythonic
> behaviour of and/or returning the "short-circuiting" object. 
> Subsequently 
>     result = hasattr(obj, 'method') and obj.method() 
> is not obvious to them but 
>     result = obj.method() if hasatttr(obj, 'method') else None
> is

I fail to see why forcing people to avoid an idiom that's obvious to 
them (because it's not the "right" one) is a benefit to their 
productivity or the readability of their code.

In my own case, although I can see that your use of "and" is shorter, I 
think that the if-else is better.  At first glance, if I see "x and 
y", it looks like x is one possible desired expression value, while 
here hasattr() makes no sense as something to store into result, so the 
second version looks more meaningful. Analyzing the code more 
carefully, I see that the two lines are different, and it seems likely 
that "None" is preferred to "False" for the result in the case when the 
obj does not have the attr.

David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at

More information about the Python-list mailing list