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
🌐
Python
peps.python.org › pep-0622
PEP 622 – Structural Pattern Matching | peps.python.org
A simple example: match shape: case Point(x, y): ... case Rectangle(x0, y0, x1, y1, painted=True): ... Whether a match succeeds or not is determined by the equivalent of an isinstance call.
🌐
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 ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-isinstance-method
isinstance() method - Python - GeeksforGeeks
July 11, 2025 - class Animal: pass class Dog(Animal): pass dog = Dog() print(isinstance(dog, Dog)) print(isinstance(dog, Animal)) ... Example 3: In this example, we check if an object is an instance of a specific type, such as a Python string or a dictionary.
🌐
W3Schools
w3schools.com › python › ref_func_isinstance.asp
Python isinstance() Function
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... The isinstance() function returns True if the specified object is of the specified type, otherwise False.
🌐
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:
🌐
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.
Find elsewhere
🌐
Python
peps.python.org › pep-0635
PEP 635 – Structural Pattern Matching: Motivation and Rationale | peps.python.org
For example: if isinstance(x, tuple) and len(x) == 2: host, port = x mode = "http" elif isinstance(x, tuple) and len(x) == 3: host, port, mode = x # Etc. Code like this is more elegantly rendered using match:
🌐
Inspired Python
inspiredpython.com › course › pattern-matching › mastering-structural-pattern-matching
Mastering Structural Pattern Matching • Inspired Python
>>> assert True == 1 >>> assert isinstance(True, bool) >>> assert isinstance(True, int) True and False are both bool and int, thus True == 1 and, in the literal pattern example above, the case True clause would never run as case 1 matches it first!
🌐
Real Python
realpython.com › what-does-isinstance-do-in-python
What Does isinstance() Do in Python? – Real Python
May 11, 2025 - To see some examples of duck typing, you’ll use the Iterable abstract base class from the collections.abc library, because isinstance() uses duck typing with many classes from this library. In Python, an iterable is an object that allows you to iterate over it.
🌐
datagy
datagy.io › home › python posts › python isinstance() function explained with examples
Python isinstance() Function Explained with Examples • datagy
March 26, 2022 - Let’s take a look at creating a list and checking its type using the isinstance() function. # Checking for Native Types Using Python isinstance() a_list = [1,2,3,4] print(isinstance(a_list, list)) # Returns: True
🌐
PYnative
pynative.com › home › python › python isinstance() function explained with examples
Python isinstance() function explained with examples
June 29, 2021 - As we can see in the output, the isinstance() returned True because num hold an integer value. Note: If the classinfo argument is not a Class, type, or tuple of types, a TypeError exception is raised. As you know, Every value (variable) in Python has a type. In Python, we can use different built-in types such as int, float, list, tuple, strings, dictionary.
🌐
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 - 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.
Published   May 02, 2021
🌐
Buddy
buddy.works › home › tutorials › languages › structural pattern matching in python
Structural Pattern Matching In Python | Tutorials
April 28, 2021 - We only want to perform the addition if both numbers are of type int. pythondef sum_two_integers(num1, num2): if isinstance(num1, int) and isinstance(num2, int): return num1 + num2
🌐
Guru99
guru99.com › home › python › type() and isinstance() in python with examples
type() and isinstance() in Python with Examples
August 12, 2024 - In this example, we are going to make use of all three params i.e name, bases, and dict in type(). ... class MyClass: x = 'Hello World' y = 50 t1 = type('NewClass', (MyClass,), dict(x='Hello World', y=50)) print(type(t1)) print(vars(t1)) ... When you pass all three arguments to type() , it ...
🌐
Career Karma
careerkarma.com › blog › python › python isinstance: a step-by-step guide
Python isinstance: A Step-By-Step Guide | Career Karma
December 1, 2023 - The syntax for isinstance() in Python is isinstance(variable_to_check, data_type). Checking the data type of a particular value is a common operation in programming. For example, you may want to check whether the value you stored in a variable ...
🌐
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): …