This tag is for questions about Python's Structural Pattern Matching feature, introduced in version 3.10
PEP 634 introduced the specification of the Structural Pattern Matching feature starting with python-3.10. In addition, PEP 635 introduces the motivations and rationale behind this new feature. Lastly, PEP 636 introduces a hands-on tutorial of the different ways to use this feature.
The feature offers a convenient, dynamic way to parse different inputs against desired patterns, and to specify the ways to handle these patterns accordingly. This is done using the new soft keywords ( i.e. they are not reserved words in other grammatical contexts) match
and case
.
For example:
match string:
case "value1":
# do something if the input is "value1"
case _:
# do something for any other case
will match the input string
against the different cases (patterns), when _
is used as a wildcard - the default case which always matches.
Some of the other useful constructs are: