This question asks for a switch/case
or match/case
equivalent in Python. It seems since Python 3.10 we can now use match/case
statement. I cannot see and understand the difference between match/case
and an if, elif
statement other than the syntactical differences!
Is there an underlying difference which makes them have different performance? or Somehow using match/case
we can control the flow better? but How? Is there an example in which match/case
is better than just an if
statement?
PEP 622 provides an in-depth explanation for how the new match-case statements work, what the rationale is behind them, and provides examples where they're better than if statements.
In my opinion the biggest improvement over if statements is that they allow for structural pattern matching, as the PEP is named. Where if statements must be provided a truthy or falsey value, match-case statements can match against the shape/structure of an object in a concise way. Consider the following example from the PEP:
def make_point_3d(pt):
match pt:
case (x, y):
return Point3d(x, y, 0)
case (x, y, z):
return Point3d(x, y, z)
case Point2d(x, y):
return Point3d(x, y, 0)
case Point3d(_, _, _):
return pt
case _:
raise TypeError("not a point we support")
It not only checks the structure of pt
, but also unpacks the values from it and assigns them to x
/y
/z
as appropriate.