选项1
我不知道对此的句法解决方案。裸变量名通常被认为是占位符(或者更正确地说:“捕获模式”)。
然而,有一个规则是合格的(即点)名称被认为是引用而不是捕获模式。如果您将变量存储another_fruit
在这样的对象中:
fruit_object = object()
fruit_object.another_fruit = "peach"
并像这样引用它:
case fruit_object.another_fruit:
print("It's a peach!")
它会按照你想要的方式工作。
选项 2
我最近还创建了一个名为 的库match-ref
,它允许您通过点名引用任何局部或全局变量:
from matchref import ref
another_fruit = "peach"
choice = "no_peach"
match choice:
case ref.another_fruit:
print("You've choosen a peach!")
它通过使用 Python 的inspect
模块来解析本地和全局命名空间(按此顺序)来做到这一点。
选项 3
当然,如果您可以接受失去一点便利,则不必安装 3rd-party 库:
class GetAttributeDict(dict):
def __getattr__(self, name):
return self[name]
def some_function():
another_fruit = "peach"
choice = "no_peach"
vars = GetAttributeDict(locals())
match choice:
case vars.another_fruit:
print("You've choosen a peach!")
这GetAttributeDict
使得使用点属性访问语法访问字典成为可能,并且locals()
是一个内置函数,用于在本地命名空间中检索所有变量作为字典。