PEP 308: A PEP Writer's Experience - PRO
David Eppstein
eppstein at ics.uci.edu
Mon Feb 10 19:06:57 EST 2003
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.
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.
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list