问题描述
Python 有能力 match values 反对像这样的文字集或占位符:
choice = "apple"
match choice:
case "plum": ...
case "cherry": ...
case another_fruit:
print("Your selected fruit is:",another_fruit)
但是,如果我们有一个名为 another_fruit
的变量并且我们想要完全匹配该变量的值,而不是分配一个具有相同名称的占位符,该怎么办?这有什么特殊的语法吗?
解决方法
选项 1
我不知道对此的句法解决方案。裸变量名称通常被视为占位符(或更准确地说:“捕获模式”)。
然而,有一条规则是限定(即带点)的名称被视为引用而不是捕获模式。如果您将变量 another_fruit
存储在这样的对象中:
fruit_object = object()
fruit_object.another_fruit = "peach"
并像这样引用它:
case fruit_object.another_fruit:
print("It's a peach!")
它会按照你想要的方式工作。
选项 2
我最近刚刚创建了 a library called 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
当然,如果您不介意失去一点便利,则不必安装第 3 方库:
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()
是一个内置函数,用于将所有变量作为本地命名空间中的 dict 检索。