[Python-ideas] Match statement brainstorm

Guido van Rossum guido at python.org
Fri May 20 13:47:19 EDT 2016


It's definitely going to be "try cases in order until one matches".

On Fri, May 20, 2016 at 10:45 AM, Paul Moore <p.f.moore at gmail.com> wrote:
> On 20 May 2016 at 17:45, Ryan Gonzalez <rymg19 at gmail.com> wrote:
>> On Fri, May 20, 2016 at 5:48 AM, Franklin? Lee
>> <leewangzhong+python at gmail.com> wrote:
>>>
>>> I think there should be different syntaxes for matching equality and
>>> binding patterns, and definitely different syntax for singular and
>>> plural cases.
>>>
>>> Let's try this:
>>> - Equality:
>>>     `case 5:`
>>> - Conditional:
>>>     `case if predicate(obj):`
>>> - Pattern-matching:
>>>     `case as [a, b, *_]:`
>>>     `case as Point(x, y):`
>>>
>>> Slightly-more-explicit checks, instead of simply `case 5:`.
>>> - `case == 5:`
>>> - `case is _sentinel:`
>>> - `case is None:`
>>> - `case < 6:`
>>> - `case in (1,2,3):`
>>> - `case in range(2, 5):`
>>> - `case in int:`
>>>
>>
>> I personally really like the equality, conditional, and pattern-matching
>> syntax you showed; it looks the most Pythonic IMO.
>
> Agreed.
>
>> However, the more explicit checks are a little overkill and feel like too
>> much special-casing. I don't know of any languages that go so far as to
>> allow stuff like `case < 6`; usually, there would instead be some syntax to
>> assign the initial object to an intermediate variable, that way you can just
>> use it with an `if` predicate.
>
> Also agreed. It seems that
>
>     switch expr as name
>         case if name is _sentinel: do_stuff()
>
> would be a reasonable syntax for naming the switch expression -
> although just giving it a name before using it in the switch is
> probably just as reasonable:
>
>     name = expr
>     switch name:
>         case if name is _sentinel: do_stuff()
>
> BTW, there's also a semantic question - if multiple cases match, would
> only one (presumably the first) or all of them be executed? I'm sure
> this was discussed to death during the discussions on PEPs 3103 and
> 275, but I don't have the time or inclination to re-read those now, so
> I'll just leave the question open here for someone else to do the
> research...
>
> Paul
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/



-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-ideas mailing list