PEP308: Yet another syntax proposal

Dave Brueck dave at pythonapocrypha.com
Mon Feb 10 17:09:44 EST 2003


On Mon, 10 Feb 2003, holger krekel wrote:

> > > > z = iif(x, x.getPref(), 'Not specified')
> > > >
> > > > is broken without short-circuiting.
> > >
> > > yes, but it is easily written with an and-expression
> > >
> > >   z = not x and 'Not specified' or x.getPref()
> >
> > Yikes! The above line of code is a great argument _in favor of_
> > if-expressions on the basis of readability and maintainability. I couldn't
> > encourage anyone to use that form.
>
> It's the "inverse" of
>
>     z = obj.method() if hasattr(obj, 'method') else None
>
> which i consider dubious compared to
>
>     z = hasattr(obj, 'method') and obj.method()

No, now the functionality has changed from returning 'Not specified' to
None. Besides, it's not just a matter of whether or not the same
functionality can be produced using a different approach, it's also about
expressing intent of the code and it's readability. For example, if I were
hunting for a bug in code that used your "not x and ..." example above,
realistically I'd slow down and review that piece over and over again each
time as it's not that obvious what is happening there (to me at least).

> > > and a ternary op would simply add another possibility.
> >
> > ...and hopefully deprecate the usage of your above example, the "simulated
> > conditional expression".
>
> citing from my last mail:
>
>     and a ternary op would simply add another possibility.

Right, I think that's the difference between our two views. IMO, the
conditional operator would *supercede* the "simulated" conditional
expressions. So you don't end up with two "valid" possibilities - you end
up with the normal way to do it and the more hacky way to do it. See, I
regard the conditional operator as something that is missing from the
language, so by adding it a hole is filled so the workaround doesn't need
to be used anymore (yes, old code will still have it, but so what? I
still have old code laying around that imports the string module). It's
the same as with any other feature that was once missing but gets added.

> Even if the old way is bad it will be useful in other situations
> Thus you still have two constructs.  In some cases PEP-308 is better,
> in others the and-idiom.  But don't forget that *both* will be abused.

I understand that both have the potential for abuse, but to me the old way
_is_ an abuse. To me this is a readable and clear idiom:

x = a or b

as is this:

x = a and b

but going beyond that in terms of complexity and relying on implicit
precedence rules (instead of grouping with parentheses) is much less
obvious and easier to screw up.

Just my two cents,
-Dave





More information about the Python-list mailing list