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
🌐
W3Schools
w3schools.com › python › ref_func_isinstance.asp
Python isinstance() Function
The isinstance() function returns True if the specified object is of the specified type, otherwise False. If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.
🌐
Python
peps.python.org › pep-0622
PEP 622 – Structural Pattern Matching | peps.python.org
Classes requiring different matching ... typing.Protocol. ... The class object for Class in Class(<sub-patterns>) is looked up and isinstance(obj, Class) is called, where obj is the value being matched....
🌐
Plain English Westminster
benhoyt.com › writings › python-pattern-matching
Structural pattern matching in Python 3.10
It has 217,000 lines of Python code, including tests. There are 1594 uses of elif, which again is 0.7%. Below are a couple of cases I saw which might benefit from pattern matching. Example from module_utils/basic.py, in _return_formatted(). Small readability improvement. def _return_formatted(self, kwargs): ... for d in kwargs['deprecations']: if isinstance(d, SEQUENCETYPE) and len(d) == 2: self.deprecate(d[0], version=d[1]) elif isinstance(d, Mapping): self.deprecate(d['msg'], version=d.get('version'), date=d.get('date'), collection_name=d.get('collection_name')) else: self.deprecate(d) ...
🌐
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.
🌐
Real Python
realpython.com › what-does-isinstance-do-in-python
What Does isinstance() Do in Python? – Real Python
May 11, 2025 - This allows you to group together multiple data types separated by the bitwise OR (|) operator. When you pass a type to be tested into isinstance(), the function will return True if the type matches any of the types defined in your union.
🌐
W3Schools
w3schools.com › python › python_match.asp
Python Match
month = 5 day = 4 match day: case 1 | 2 | 3 | 4 | 5 if month == 4: print("A weekday in April") case 1 | 2 | 3 | 4 | 5 if month == 5: print("A weekday in May") case _: print("No match") Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
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
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.
🌐
W3schools-fa
w3schools-fa.ir › python › ref_func_isinstance.html
Python isinstance() Function
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords ... The isinstance() function returns True if the specified object is of the specified type, otherwise False.
🌐
Cach3
w3schools.com.cach3.com › python › ref_func_isinstance.asp.html
Python isinstance() Function - W3Schools
Python Examples Python Exercises Python Quiz Python Certificate ... The isinstance() function returns True if the specified object is of the specified type, otherwise False.
🌐
W3Schools
w3schools.com › python › python_booleans.asp
Python Booleans
Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:
🌐
W3Schools
w3schools.com › python › ref_func_issubclass.asp
Python issubclass() Function
Python Examples Python Compiler ... of the specified object, otherwise False. ... The isinstance() function, to check if an object is of a certain type....
🌐
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:
🌐
datagy
datagy.io › home › python posts › python isinstance() function explained with examples
Python isinstance() Function Explained with Examples • datagy
March 26, 2022 - In this tutorial, you’ll learn how the Python isinstance function works and how it can be used in your Python programming. The Python isinstance() function allows you to check if an object belongs to a particular data type or class. Further, ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Get and Check the Type of an Object in Python: type(), isinstance() | note.nkmk.me
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.
🌐
PYnative
pynative.com › home › python › python isinstance() function explained with examples
Python isinstance() function explained with examples
June 29, 2021 - For example, isinstance(name, str) checks if name is an instance of a class str. Also, Solve: Python Basic Exercise and Beginners Quiz
🌐
Python Pool
pythonpool.com › home › blog › match case python: new addition to the language
Match Case Python: New Addition to the Language - Python Pool
January 9, 2022 - Cube is: 857.375 >>> n = 9 >>> is_int = isinstance(n, int) >>> match is_int: ... case True : print("Square is :",calc(n)) ... case False : print("Cube is:", calc(n)) ... # Square is : 729 ... Square is : 729 >>> ... Correct. I’ve updated the post accordingly. ... Python Pool is a platform where you can learn and become an expert in every aspect of Python programming language as well as in AI, ML, and Data Science.