与具有关键字属性的class-pattern匹配时,是否可以将属性直接绑定到变量?
对于位置参数,可以通过海象运算符: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
_id: str = node.value.id # mypy: [name-defined, attr-defined]
当然可以做类似
case ast.Attribute(value=ast.Name()) as attr
的事情,然后使用 attr.value
,但是 mypy
不喜欢这样,并声称 attr.value
是 expr
而不是 ast.Name
。
好吧,事实证明我们甚至可以在类模式中使用
as
模式
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)