match-case: Bind keyword attribute to variable

59 Views Asked by At

When matching against a class-pattern with keyword attributes, is it possible to bind the attribute to a variable directly?

For positional arguments, it is possible via walrus operator: https://peps.python.org/pep-0622/#walrus-patterns

import ast
tree = ast.parse('foo.bar = 2')
for node in ast.walk(tree):
    match node:
        case ast.Attribute(value=ast.Name()):
            # how to bind value directly?
            print(node)
            print(value)  # name value is not defined

One could of course do something like case ast.Attribute(value=ast.Name()) as attr and then use attr.value, but mypy doesn't like this and claims that attr.value is an expr and not an ast.Name.

match node:
    case ast.Attribute(value=ast.Name()) as attr:
        name: str = attr.value.id  # mypy: "expr" has no attribute "id"
1

There are 1 best solutions below

0
On

Ok, turns out we can use as-pattern even inside the class pattern

import ast
tree = ast.parse('foo.bar = 2')
for node in ast.walk(tree):
    match node:
        case ast.Attribute(value=ast.Name() as value) as attr:
            print(attr)
            print(value)