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.

Answer from Raymond Hettinger on Stack Overflow
🌐
Henryiii
henryiii.github.io › level-up-your-python › notebooks › 2.8 Pattern Matching.html
17. Structural Pattern Matching (Python 3.10+) — Level Up Your Python
Classes match via isinstance; if you give an “empty” class, you can access it using the original match argument:
Discussions

Anyone used match case yet?
Last I used match/case, I used it as a replacement to isinstance. match/case + dataclasses + "mypy static typing" work together to help me get exhaustive type-casing and destructuring. More on reddit.com
🌐 r/Python
82
80
January 27, 2024
Type narrowing with ``isinstance`` and ``issubclass`` in match statement
Python version (and distribution if applicable, e.g. Anaconda): 3.10.0a7 ... An isinstance or issubclass call in a match statement should narrow the type just like the same call in an if statement. More on github.com
🌐 github.com
6
May 2, 2021
You can use 3.10's new structural pattern matching feature to easily flatten deeply nested lists, tuples and sets.
I programmatically solved this in python 3.8, I'm excited to see how 3.10 simplifies this. Thanks for the post More on reddit.com
🌐 r/Python
60
534
November 22, 2021
Use a typeddict as the `case` guard to match structure
I would like to use typeddicts as the case guards in a match statement: from typing import TypedDict class A(TypedDict): x: int class B(TypedDict): y: int def func(value): match value: case A: … More on discuss.python.org
🌐 discuss.python.org
1
November 22, 2024
🌐
Python Morsels
pythonmorsels.com › match-case-parsing-python
Appreciating Python's match-case by parsing Python code - Python Morsels
June 22, 2022 - Seeing those isinstance checks in particular made me think "wait a minute, match-case was made for this!" After introspecting (via breakpoint and Python's debugging friends), I found that I could refactor the above if-elif into this equivalent match-case block:
🌐
Python
peps.python.org › pep-0622
PEP 622 – Structural Pattern Matching | peps.python.org
Classes requiring different matching ... object for Class in Class(<sub-patterns>) is looked up and isinstance(obj, Class) is called, where obj is the value being matched....
🌐
W3Schools
w3schools.com › python › ref_func_isinstance.asp
Python isinstance() Function
Python Examples Python Compiler ... Python Training ... The isinstance() function returns True if the specified object is of the specified type, otherwise False....
🌐
Plain English Westminster
benhoyt.com › writings › python-pattern-matching
Structural pattern matching in Python 3.10
Originally I was also concerned that match’s class patterns don’t play well with Python’s use of duck typing, where you just access attributes and call methods on an object, without checking its type first (for example, when using file-like objects). With class patterns, however, you specify the type, and it performs an isinstance check.
🌐
Python
peps.python.org › pep-0636
PEP 636 – Structural Pattern Matching: Tutorial | peps.python.org
Rather than writing multiple isinstance() checks, you can use patterns to recognize different kinds of objects, and also apply patterns to its attributes: match event.get(): case Click(position=(x, y)): handle_click_at(x, y) case KeyPress(k...
Find elsewhere
🌐
Real Python
realpython.com › what-does-isinstance-do-in-python
What Does isinstance() Do in Python? – Real Python
July 21, 2025 - Python’s isinstance() function helps you determine if an object is an instance of a specified class or its superclass, aiding in writing cleaner and more robust code. You use it to confirm that function parameters are of the expected types, ...
🌐
Hillel Wayne
hillelwayne.com › post › python-abc
Crimes with Python's Pattern Matching
July 31, 2022 - class PalindromicName(ABC): @classmethod def __subclasshook__(cls, C): name = C.__name__.lower() return name[::-1] == name class Abba: ... class Baba: ... >>> isinstance(Abba(), PalindromicName) True >>> isinstance(Baba(), PalindromicName) False · You can do some weird stuff with this. Back in 2019 I used it to create non-monotonic types, where something counts as a NotIterable if it doesn’t have the __iter__ method. There wasn’t anything too diabolical you could do with this: nothing in Python really interacted with ABCs, limiting the damage you could do with production code. Then Python 3.10 added pattern matching.
🌐
GitHub
github.com › microsoft › pylance-release › issues › 1221
Type narrowing with ``isinstance`` and ``issubclass`` in match statement · Issue #1221 · microsoft/pylance-release
May 2, 2021 - class Custom: pass class Derived(Custom): pass def func(cls: Custom) -> Derived: var: Derived match isinstance(cls, Derived): case True: var = cls case _: var = Derived() return var
Published   May 02, 2021
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-isinstance-method
isinstance() method - Python - GeeksforGeeks
July 11, 2025 - isinstance() is a built-in Python function that checks whether an object or variable is an instance of a specified type or class (or a tuple of classes), returning True if it matches and False otherwise, making it useful for type-checking and ...
🌐
Python.org
discuss.python.org › python help
Use a typeddict as the `case` guard to match structure - Python Help - Discussions on Python.org
November 22, 2024 - I would like to use typeddicts as the case guards in a match statement: from typing import TypedDict class A(TypedDict): x: int class B(TypedDict): y: int def func(value): match value: case A: print("it's an A") case B: print("it's a B") case _: print("it's neither") func({"y": 1}) # should print 'it's a B" # instead I get this error: # SyntaxError: name capture 'A' makes remaining patterns unreachable Why is thi...
🌐
Vultr
docs.vultr.com › python › examples › differentiate-between-type-and-isinstance
Python Program to Differentiate Between type() and isinstance() | Vultr Docs
September 27, 2024 - python Copy · class Base: pass class Derived(Base): pass derived_instance = Derived() # Using type() print(type(derived_instance) == Base) # Outputs: False # Using isinstance() print(isinstance(derived_instance, Base)) # Outputs: True Explain Code · Here, type() checks for exact type matching, while isinstance() considers the inheritance chain.
🌐
Python
peps.python.org › pep-0635
PEP 635 – Structural Pattern Matching: Motivation and Rationale | peps.python.org
In Python, we simply use isinstance() together with the __match_args__ field of a class to check whether an object has the correct structure and then transform some of its attributes into a tuple.
🌐
GitHub
github.com › python › cpython › issues › 106246
[match-case] Allow matching Union types · Issue #106246 · python/cpython
May 21, 2023 - from typing import TypeAlias Numeric: TypeAlias = int | float assert isinstance(1.2, Numeric) # ✔ match 1.2: case Numeric(): # TypeError: called match pattern must be a type pass · This carries extra benefits, as TypeAliases are kind of necessary to write legible code when working with large unions, such as e.g. PythonScalar: TypeAlias = None | bool | int | float | complex | bool | str | datetime | timedelta.
Published   Jun 29, 2023
🌐
Note.nkmk.me
note.nkmk.me › home › python
Get and Check the Type of an Object in Python - nkmk note
April 22, 2025 - type() returns True only when the types match exactly, but isinstance() returns True for instances of both the specified class and its subclasses.
🌐
Python.org
discuss.python.org › python help
How to make the match statement work? - Python Help - Discussions on Python.org
November 10, 2021 - Trying to learn Python 3.10 pattern matching. Tried this example after reading 8.6.4.9. Mapping Patterns >>> match 0.0: ... case int(0|1): ... print(1) ... Traceback (most recent call last): …
🌐
ArjanCodes
arjancodes.com › blog › how-to-use-structural-pattern-matching-in-python
Introduction to Structural Pattern Matching in Python | ArjanCodes
June 20, 2024 - If you’ve spent any time with isinstance and hasattr, you know the pain. These methods work, but they’re often clunky and cumbersome. What if there was a more elegant solution that not only simplifies your code but also makes it more readable? The answer is Structural Pattern Matching (SPM).