PEP 308: A PEP Writer's Experience - PRO

holger krekel pyth at devel.trillke.net
Tue Feb 11 01:36:20 CET 2003


David Eppstein wrote:
> On 2/11/03 12:53 AM +0100 holger krekel <pyth at devel.trillke.net> wrote:
> >> > 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.
> >
> > because it easily leads to
> >
> >     if obj.method() if hasattr(obj, 'method') else None:
> >
> > which you have a harder time to justify as nice, not?
> 
> Different expressions are better in different contexts -- the "and" version 
> clearly works better as an if condition, but I think the ternary version 
> works better in an assignment.

I agree.  But i don't want to have such special casing. 

> If a programmer is intent on using a ternary in an if, I'd at least prefer 
> something like your example above that stands out as being unstylish and in 
> need of rewriting.  Consider the alternative: a programmer intending a 
> ternary who writes it as
>     if hasattr(obj, 'method') and obj.method() or some_default_value:
> It would be much harder to notice that this is buggy (in the case where 
> obj.method returns false but some_default_value is true), because of the 
> naturality of finding ands and ors in an if condition.

I agree but my conclusion is going to multiple lines and have
some vertical/indentation clue instead of having to parse it
"manually".  The 10 seconds save in writing it i easily loose
the next 5 times i come back to the function changing it. 

    holger





More information about the Python-list mailing list