Python 3.10 match/case with constants [duplicate]
I tried to replace an if/elif/elif/.../else code block with the shorter match/case
from Python 3.10.
I have three constants defined and want to do something different for each one, so my code looks roughly like this:
>>> const_a = 1
>>> const_b = 2
>>> const_c = 3
>>> interface = const_b # example
>>> match interface:
... case const_a:
... print("case a")
... case const_b:
... print("case b")
... case const_c:
... print("case c")
However, when running this code, there will be an Exception:
File "<stdin>", line 2
SyntaxError: name capture 'const_a' makes remaining patterns unreachable
What am I doing wrong?
The match...case
is more than just a switch...case
. From https://www.python.org/dev/peps/pep-0622/#patterns:
- A capture pattern looks like x and is equivalent to an identical assignment target: it always matches and binds the variable with the given (simple) name.
- A constant value pattern works like the literal but for certain named constants. Note that it must be a qualified (dotted) name, given the possible ambiguity with a capture pattern. It looks like Color.RED and only matches values equal to the corresponding value. It never binds.
So you're going to have to create an object that has those variables as attributes and use the qualified names in the match
import types
consts = types.SimpleNamespace()
consts.A = 1
consts.B = 2
consts.C = 3
interface = 2
match interface:
case consts.A:
print("A")
case consts.B:
print("B")
case consts.C:
print("C")
Which, as expected, prints B
For more information on why, see https://www.python.org/dev/peps/pep-0622/#alternatives-for-constant-value-pattern