[Python-ideas] Match statement brainstorm
Guido van Rossum
guido at python.org
Mon May 23 19:13:23 EDT 2016
On Mon, May 23, 2016 at 3:49 PM, Michael Selik <michael.selik at gmail.com> wrote:
>
>
> On Mon, May 23, 2016 at 3:58 PM Guido van Rossum <guido at python.org> wrote:
>>
>> On Mon, May 23, 2016 at 11:45 AM, Joao S. O. Bueno
>> <jsbueno at python.org.br> wrote:
>> > I still fail to see what justifies violating The One Obvious Way to Do
>> > It which uses an if/elif sequence
>>
>> Honestly I'm not at all convinced either! If it was easy to do all
>> this with a sequence of if/elif clauses we wouldn't need it. The
>> problem is that there are some types of matches that aren't so easy to
>> write that way, e.g. combining an attempted tuple unpack with a guard,
>> or "instance unpack" (check whether specific attributes exist)
>> possibly combined with a guard. (The tricky thing is that the guard
>> expression often needs to reference to the result of the unpacking.)
>
>
> Wouldn't an exception-catching expression (PEP 463) enable most of what you
> want with the existing if/elif/else chain?
>
> def demo(arg):
> if ((arg.x, arg.y) except AttributeError: False):
> print('x=', arg.x, 'y=', arg.y)
> elif ((arg[0], arg[1]) except IndexError: False):
> a, b, *_ = arg
> print('a=', a, 'b=', b)
> else:
> print('Too bad')
>
>
> To get everything you want, we could have an exception-catching assignment
> expression. While a plain ``=`` assignment would be problematic as an
> expression due to the common ``==`` typographical error, a less error-prone
> operator might be OK. I'd suggested ``?=`` earlier in the thread, but
> perhaps I didn't write out a good example at that time. Here's one that's
> closer to the original demo example.
>
> def demo(arg):
> if p, q ?= arg.x, arg.y: print('x=', p, 'y=', q)
> elif a, b, *_ ?= arg: print('a=', a, 'b=', b)
> else: print('Too bad')
>
>
> I figure it's better to solve the category of problems -- exception-catching
> expressions -- rather than the single problem of catching exceptions in an
> if/elif/else chain. Or do you think this is too much temptation for
> unreadable code golf?
People are likely either going to put in exceptions that don't catch
enough (e.g. IndexError isn't the only exception that example can
throw) or, overreacting to that problm, that catch everything ("except
Exception:" is an anti-pattern that's hard to fight).
Plus there's the redundancy that you showed.
--
--Guido van Rossum (python.org/~guido)
More information about the Python-ideas
mailing list