[Python-ideas] Match statement brainstorm
Nikolaus Rath
Nikolaus at rath.org
Thu May 26 14:21:50 EDT 2016
On May 25 2016, "Franklin? Lee" <leewangzhong+python-Re5JQEeQqe8AvxtiuMwx3w at public.gmane.org> wrote:
> On Wed, May 25, 2016 at 1:52 AM, Nick Coghlan <ncoghlan-Re5JQEeQqe8AvxtiuMwx3w at public.gmane.org> wrote:
>> Using the running demo:
>>
>> def demo(arg):
>> given arg:
>> case x, y, *_: # Tuple matching (implicit name binding)
>> ...
>> case (.x, .y) as p, q: # Attribute matching
>> ...
>> case (["x"], ["y"]) as p, q: # Item matching
>> ...
>> case (.x) as p and isinstance(p, int): # Match + condition
>> ...
>> case if isinstance(arg, int): # Condition only
>> ...
>> else: # Default
>> ...
>>
>> The other key change there is introducing "as" to the individual cases
>> in order to be able to separate the match pattern definition from the
>> local name binding.
>
> I still don't like that `case THING` is a pattern, rather than a value
> to test against. Here's my modifications with "as", attributes, and
>
> def demo(arg):
> given arg:
> case as x, y, *_: # Tuple matching (implicit name binding)
> ...
> case as object(x=p, y=q, **_): # Attribute matching
> ...
> case as {'x': p, 'y', q, **_}: # Item matching
> ...
> case as object(x=p, **_) and isinstance(p, int): # Match + condition
> ...
> case if isinstance(arg, int): # Condition only
> ...
> else: # Default
I think all the ideas with "as" are difficult to read. I think its much
better to embed the target variables in the pattern - we just need a way
to mark them as such.
Mathematica has the same problem and solves it with a trailing _, but we
can't do that because our variables names may contain them. But maybe we
could use $? Most people already strongly associate this with variables.
Example:
given foo
case (x,y):
# matches if foo == (x,y)
case (x, $y):
# matches if len(foo) == 2 and foo[0] == x,
# and assigns y = foo[1]
case {'bar': $x, y: $z}:
# matches if foo is a map that has 'bar' and y keys
# and assigns x = foo['bar'], z = foo[y]
case $x.bar:
# matches if hasattr(foo, 'bar') and assigns x = foo
Best,
-Nikolaus
--
GPG encrypted emails preferred. Key id: 0xD113FCAC3C4E599F
Fingerprint: ED31 791B 2C5C 1613 AF38 8B8A D113 FCAC 3C4E 599F
»Time flies like an arrow, fruit flies like a Banana.«
More information about the Python-ideas
mailing list