Style question for conditional execution

Asun Friere afriere at yahoo.co.uk
Wed Nov 24 19:45:52 EST 2010


On Nov 25, 7:43 am, Paul Rubin <no.em... at nospam.invalid> wrote:
> Gerald Britton <gerald.brit... at gmail.com> writes:
> >     if v:
> >         f()
>
> > I might, however, think more in a functional-programming direction.
> > Then I might write:
>
> >     v and f()
>
> Python has conditional expressions.  The above would be:
>
>     f() if v else None
>
> using "and" is bug-prone.

Using 'and' is indeed bug-prone when used in combination with 'or' to
achieve a ternary conditional op, as was done the pre PEP308 days, eg
"val = cond and a or b" because of the possibility that 'a' was itself
not true, (thus requiring the ugly 'val = (cond and [a] or [b])[0]').

But no such bug could occur with this particular idiom. What could
possibly go wrong here? :)

That being said, I agree with previous posters that "if cond : fn()"
wins in terms of readability.



More information about the Python-list mailing list