[Python-ideas] If branch merging

Chris Angelico rosuav at gmail.com
Mon Jun 8 04:45:49 CEST 2015

On Mon, Jun 8, 2015 at 12:33 PM, Stephen J. Turnbull <stephen at xemacs.org> wrote:
> I'm definitely -1 on the also, alif syntax at this point.  On the
> other hand, having done a lot of C programming in my misspent youth, I
> do miss anaphoric conditionals, so I too would like to see the
> possibility of "if cond as var: do_something_with_var" explored.  Of
> course Nick is right that automatic common subexpression elimination
> (CSE) is the big win, but manual CSE can improve readability.

Part of the trouble with depending on CSE is that Python is so dynamic
that you can't depend on things having no side effects... but the more
important part, in my opinion, is that duplication is a source code
maintenance problem. Bruce suggested this:

x = a and a.b and a.b.c and a.b.c.d
# which becomes
x = a and a.b
if x: x = x.c
if x: x = x.d

and frankly, I'd be more worried about a subsequent edit missing
something than I would be about the performance of all the repeated
lookups. Of course, Python does have an alternative, and that's to use
attribute absence rather than falsiness:

try: x = a.b.c.d
except AttributeError: x = None

But that won't always be an option. And any kind of expression that
says "the thing on the left, if it's false, otherwise the thing on the
left modified by this operator" is likely to get messy in anything
more than trivial cases; it looks great here:

x = a?.b?.c?.d

but now imagine something more complicated, and it's a lot more messy.


More information about the Python-ideas mailing list