pythonstructural-pattern-matching

What explains pattern matching in Python not matching for 0.0, but matching for float()?


I would like to understand how pattern matching works in Python.

I know that I can match a value like so:

>>> t = 12.0
>>> match t:
...   case 13.0:
...     print("13")
...   case 12.0:
...     print("12")
...
12

But I notice that when I use matching with a type like float(), it matches 12.0:

>>> t = 12.0
>>> match t:
...   case float():
...     print("13")
...   case 12.0:
...     print("12")
...
13

This seems strange, because float() evaluates to 0.0, but the results are different if that is substituted in:

>>> t = 12.0
>>> match t:
...   case 0.0:
...     print("13")
...   case 12.0:
...     print("12")
...
12

I would expect that if 12.0 matches float(), it would also match 0.0.

There are cases where I would like to match against types, so this result seems useful. But why does it happen? How does it work?


Solution

  • The thing that follows the case keyword is not an expression, but special syntax called a pattern.

    0.0 is a literal pattern. It checks equality with 0.0.

    float() is a class pattern. It checks that the type is float. Since it is not an expression, it isn't evaluated and therefore is different from 0.0.