Skip to content

[mypyc] Fix binding of "as" patterns in match statements - #22572

Open
andriisem wants to merge 1 commit into
python:masterfrom
andriisem:mypyc-match-as-capture
Open

andriisem wants to merge 1 commit into
python:masterfrom
andriisem:mypyc-match-as-capture

Conversation

@andriisem

Copy link
Copy Markdown

compiled as patterns in match statements bind the name wrong

def f(x: object) -> object:
    match x:
        case [a, b] as z:
            return z
    return None

f([1, 2])  # UnboundLocalError, expected [1, 2]
  • sequence or mapping subpattern: name is never bound
  • case [1, *_] as z: z is the item 1, not the subject
  • case 1.0 as z: z is the literal, so f(1) returns 1.0

only value and class patterns bound the name, and the value pattern used the literal. now visit_as_pattern binds the subject after the subpattern matches. this removes bind_as_pattern and the workaround in visit_or_pattern

The name in `case <pattern> as z` was only bound by value and class
patterns, via a pending `as_pattern` that the subpattern visitor had to
pick up. Sequence and mapping patterns never bound it, so `z` raised
UnboundLocalError. Value patterns bound the pattern value instead of
the subject, so `case 1.0 as z` gave `z == 1.0` for subject `1` or `True`.

Bind the name in visit_as_pattern itself, to the subject, in the block
reached when the subpattern matched. This also removes the or-pattern
workaround.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant