Example converted to pattern matching
Here's the equivalent code using match and case:
match x:
case int():
pass
case str():
x = int(x)
case float() | Decimal():
x = round(x)
case _:
raise TypeError('Unsupported type')
Explanation
PEP 634, available since Python 3.10, specifies that isinstance() checks are performed with class patterns. To check for an instance of str, write case str(): .... Note that the parentheses are essential. That is how the grammar determines that this is a class pattern.
To check multiple classes at a time, PEP 634 provides an or-pattern using the | operator. For example, to check whether an object is an instance of float or Decimal, write case float() | Decimal(): .... As before, the parentheses are essential.
Example converted to pattern matching
Here's the equivalent code using match and case:
match x:
case int():
pass
case str():
x = int(x)
case float() | Decimal():
x = round(x)
case _:
raise TypeError('Unsupported type')
Explanation
PEP 634, available since Python 3.10, specifies that isinstance() checks are performed with class patterns. To check for an instance of str, write case str(): .... Note that the parentheses are essential. That is how the grammar determines that this is a class pattern.
To check multiple classes at a time, PEP 634 provides an or-pattern using the | operator. For example, to check whether an object is an instance of float or Decimal, write case float() | Decimal(): .... As before, the parentheses are essential.
Using python match case
Without Exception handling
match x:
case int():
pass
case str():
x = int(x)
case float() | Decimal():
x = round(x)
case _:
raise TypeError('Unsupported type')
Some extras
There are still some flows in this code.
With exception handling
match x:
case int():
pass
case str():
try:
x = int(x)
except ValueError:
raise TypeError('Unsupported type')
case float() | Decimal():
x = round(x)
case _:
raise TypeError('Unsupported type')
As a function
def func(x):
match x:
case int():
pass
case str():
try:
x = int(x)
except ValueError:
raise TypeError('Unsupported type')
case float() | Decimal():
x = round(x)
case _:
raise TypeError('Unsupported type')
return x
What are your thoughts on it.
It's a pretty nifty feature and it's a much easier to extend or extend, like selectively flattening some values in a dictionary based on the key, for instance. I've written about it extensively on Mastering Structural Pattern Matching