2

I've found an unexpected behaviour for Python structural pattern matching that I want to discuss today.
All the code there is run with CPython 3.10.8

So, let's take a look on the code below

match str(True):
     case str(True): print(1)
     case str(False): print(2)
     case _: print(3)

I expect this code to print 1. The reason for that is that str(True) will evaluate into "True" in both match part and case part. I expect "True" to match "True". However, surprisingly for me, this code print 3.

We can also rewrite this into this piece of code:

match str(True):
    case "True": print(1)
    case "False": print(2)
    case _: print(3)

This time this code will print 1.

What happening there? Why python pattern match working differently depending on whether there is an expression after "case" word or not. Should evaluations be forbidden in pattern-matching? What is rationale behind this?

inyutin
  • 406
  • 3
  • 9
  • The cases are trying to match a pattern. You *can* match against a class like `str`, but the correct way to do that would be `case str("True"):` or `case str(p): print(p)` to extract p, which is probably not your intent here. – Mark Jan 02 '23 at 20:24

1 Answers1

0

The reason for this behavior is that the match statement is designed to work with literal values as patterns, rather than expressions. It is not intended to evaluate expressions as patterns.

Therefore, the recommended way to use the match statement is to use literal values as patterns, rather than expressions. This will ensure that the pattern matching works as expected.

You can read more about it here.

joeyagreco
  • 98
  • 2
  • 11
  • The link that you give shows that the pattern syntax extends beyond literal values. – John Coleman Jan 02 '23 at 23:24
  • For the sake of this example, literal values are what should be used. What OP was looking for is not supported: https://peps.python.org/pep-0634/#patterns – joeyagreco Jan 03 '23 at 06:18