Python's match
is much more than a simple switch statement. If you use bare what you consider "variable names", they are actually going to be Capture Patterns. as per definition in PEP no. 634
Besides the fact that you should probably not use match
for your use case, you have to use qualified (dotted) names in one of the following ways:
#1 Flat Object
statuses = object()
statuses.success = 200
status.not_found = 404
def handle(retcode):
match retcode:
case statuses.success: print("Success")
case statuses.not_found: print("Not found")
#2 Object Oriented Programming
class StatusValues:
success = 200
not_found = 404
def handle(retcode):
match retcode:
case StatusValues.success: print("Success")
case StatusValues.not_found: print("Not found")
#3 Simple qualified locals()/globals() access
I've developed the match-ref library which allows you to access any local or global variable in- or outside of any function, simply using the ref.
prefix.
from matchref import ref
import random
SUCCESS = 200
NOT_FOUND = 404
def handle(retcode):
random_code = random.randint(600,699)
match retcode:
case ref.SUCCESS: print("Success")
case ref.NOT_FOUND: print("Not found")
case ref.random_code: print("OK, you win!")
As you can see, ref
automatically resolved variables from your local and global namespaces (in this order). There's no additional setup necessary.
If you don't want to use 3rd-party libraries, you can see a slightly similar no-libraries version below.
#4 Qualified locals()/globals() access without 3rd-party libs
locals()
and globals()
are built-in functions in Python which return a dict
containing all your variable names mapped to their respective values. You need to be able to access the dict's values using dotted syntax, since match
also does not support dictionary access syntax. You can therefore write this simple helper class:
class GetAttributeDict(dict):
def __getattr__(self, name):
return self[name]
and use it like so:
import random
SUCCESS = 200
NOT_FOUND = 404
def handle(retcode):
random_code = random.randint(600, 699)
globs = GetAttributeDict(globals())
locs = GetAttributeDict(locals())
match retcode:
case globs.SUCCESS: print("Success")
case globs.NOT_FOUND: print("Not found")
case locs.random_code: print("OK , you win!")
#5 Module Access
Given that you seem to intend to re-use your status codes (because otherwise you could inline them in your case
s), you might consider using separate modules for this.
constants.py:
SUCCESS = 200
NOT_FOUND = 404
main.py
import constants
match retcode:
case constants.SUCCESS: ...
...
Again, you might want to reconsider if you want to use match
at all.
SUCCESS
should be interpreted as a capture pattern.