Option 1
I don't know of a syntactic solution to this. Bare variable names are usually considered placeholders (or to be more correct: "capture patterns").
There is however the rule that qualified (i.e. dotted) names are considered references and not capture patterns. If you stored your variable another_fruit
in an object like this:
fruit_object = object()
fruit_object.another_fruit = "peach"
and referenced it like this:
case fruit_object.another_fruit:
print("It's a peach!")
it will work the way you want.
Option 2
I've also just very recently created a library called match-ref
, which allows you to reference any local or global variable via a dotted name:
from matchref import ref
another_fruit = "peach"
choice = "no_peach"
match choice:
case ref.another_fruit:
print("You've choosen a peach!")
It does this by making use of Python's inspect
module for resolving your local and global namespaces (in this order).
Option 3
Of course, you don't have to install a 3rd-party library if you are ok with losing a little bit of convenience:
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!")
The GetAttributeDict
makes it possible to access a dictionary using dotted attribute access syntax and locals()
is a builtin function to retrieve all variables as a dict in the local namespace.