Questions tagged [structural-pattern-matching]

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 . 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:

52 questions
72
votes
6 answers

How to use values stored in variables as case patterns?

I'm trying to understand the new structural pattern matching syntax in Python 3.10. I understand that it is possible to match on literal values like this: def handle(retcode): match retcode: case 200: print('success') …
54
votes
2 answers

How to perform approximate structural pattern matching for floats and complex

I've read about and understand floating point round-off issues such as: >>> sum([0.1] * 10) == 1.0 False >>> 1.1 + 2.2 == 3.3 False >>> sin(radians(45)) == sqrt(2) / 2 False I also know how to work around these issues with math.isclose() and…
35
votes
3 answers

How to do an else (default) in match-case?

Python recently has released match-case in version 3.10. The question is how can we do a default case in Python? I can do if/elif but don't know how to do else. Below is the code: x = "hello" match x: case "hi": print(x) case "hey": …
farhan jatt
  • 509
  • 1
  • 8
  • 31
27
votes
2 answers

Capture makes remaining patterns unreachable

Why does this code fail: OKAY = 200 NOT_FOUND = 404 INTERNAL_SERVER_ERROR = 500 match status: case OKAY: print('It worked') case NOT_FOUND: print('Unknown') case INTERNAL_SERVER_ERROR: print('Out of service') …
27
votes
2 answers

Convert multiple isinstance checks to structural pattern matching

I want to convert this existing code to use pattern matching: if isinstance(x, int): pass elif isinstance(x, str): x = int(x) elif isinstance(x, (float, Decimal)): x = round(x) else: raise TypeError('Unsupported type') How do you…
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
19
votes
4 answers

Structural pattern matching using regex

I have a string that I'm trying to validate against a few regex patterns and I was hoping since Pattern matching is available in 3.10, I might be able to use that instead of creating an if-else block. Consider a string 'validateString' with possible…
18
votes
1 answer

How can I apply gettext translations to string literals in case statements?

I need to add gettext translation to all the string literals in our code, but it doesn't work with literals in case statements. This failed attempt gives SyntaxError: Expected ':': from gettext import gettext as _ direction = input(_('Enter a…
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
10
votes
1 answer

Avoiding accidental capture in structural pattern matching

This example is being discussed as likely "gotcha" when using pattern matching: NOT_FOUND = 400 retcode = 200 match retcode: case NOT_FOUND: print('not found') print(f'Current value of {NOT_FOUND=}') This is an example of accidental…
8
votes
3 answers

How to use python's Structural Pattern Matching to test built in types?

I'm trying to use SPM to determine if a certain type is an int or an str. The following code: from typing import Type def main(type_to_match: Type): match type_to_match: case str(): print("This is a String") case…
Curtwagner1984
  • 1,908
  • 4
  • 30
  • 48
8
votes
4 answers

Python Structural Pattern Matching

I'm not able to run this code: match shape: case Point(x, y): ... case Rectangle(x, y, _, _): ... print(x, y) I can't find the match keyword in Python. I found it here:…
5
votes
1 answer

Point() accepts 0 positional sub-patterns (2 given)

I'm trying to run an example from the docs, but get the error: Traceback (most recent call last): File "", line 2, in TypeError: Point() accepts 0 positional sub-patterns (2 given) Can someone explain what I doing wrong…
5
votes
1 answer

Is there a way to test if an Iterable contains a pattern using python's "match" statement?

This has to do with the new Python 3.10 beta and the new match syntax. Is there any way to check if a pattern is simply contained in an iterable? the most obvious solution, to simply put two wildcards on either side, but that raises a SyntaxError…
5
votes
1 answer

How to express hasattr() duck typing logic with structural pattern matching?

I have code that checks for named tuples and dataclasses by looking for a _fields attribute: if hasattr(candidate, '_fields'): do_action() How can I express this with Python 3.10's match/case structural pattern matching?
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
4
votes
2 answers

How to match an empty dictionary?

Python supports Structural Pattern Matching since version 3.10. I came to notice that matching an empty dict doesn't work by simply matching {} as it does for lists. According to my naive approach, non-empty dicts are also matched (Python…
upe
  • 1,862
  • 1
  • 19
  • 33
4
votes
2 answers

Structural pattern matching python - match at any position in sequence

I have a list of objects, and want to check if part of the list matches a specific pattern. Consider the following lists: l1 = ["foo", "bar"] l2 = [{1, 2},"foo", "bar"] l3 = ["foo", "bar", 5] l4 = [{1,2},"foo", "bar", 5, 6] How would I match the…
j0nny80ss
  • 43
  • 4
1
2 3 4