[Python-ideas] If branch merging

Andrew Barnert abarnert at yahoo.com
Mon Jun 8 05:05:49 CEST 2015

On Jun 7, 2015, at 19:45, Chris Angelico <rosuav at gmail.com> wrote:

> 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.

I don't have a link, but one of the Swift development blogs shows a number of good examples where it isn't an option. When deciding whether they wanted SmallTalk-style nil chaining or Python-style AttributeError/LookupError, all the simple cases look just as good both ways. So they went out looking for real-life code in multiple languages to find examples that couldn't be translated to the other style. They found plenty of nil-chaining examples that were clumsy to translate to exceptions, but almost all of the exception examples that were clumsy to translate to nil chaining could be solved if they just had multiple levels of nil. So, if they could find a way to provide something like Haskell's Maybe, but without forcing you to think about monads and pattern matching, that would be better than exceptions. So that's what they did. (I'm not sure it's 100% successful, because there are rare times when you really do want to check for Just Nothing, and by hiding things under the covers they made that difficult... But in simple cases it definitely does work.)

Anyway, their language design choice isn't directly relevant here (I assume nobody wants a.b.c.d to be None of a.b is missing, or wants to add a?.b?.c?.d syntax to Python), but the examples probably are.

> 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.

It's surprising how often it doesn't get messy in Swift. But when it does, I really miss being able to pattern match Just Nothing, and there's no way around that without two clumsy assignment statements before the conditional (or defining and calling an extra function), which is even worse than the one that Python often needs...

More information about the Python-ideas mailing list