mathspp
  • Blog
    • Pydon'ts
    • Problems
    • TIL
    • Twitter threads
  • Books
  • Talks
  • Trainings
    • Advanced iteration
    • Python for scripting and automation
    • Rust for Python developers
  • Courses
  • About
Link blog

Crimes with Python's Pattern Matching

by Hillel Wayne on 22-08-2025 22:16

In this article, Hillel abuses using __subclasshook__ in abstract base classes when used in conjunction with structural pattern matching. As an example, define

from abc import ABC

class NotIterable(ABC):
    @classmethod
    def __subclasshook__(cls, C):
        return not hasattr(C, "__iter__")

Now, you can use NotIterable() in a match ...: case ...: to match non-iterable values:

def wtp(value):
    match value:
        case NotIterable():
            print("Not an iterable.")
        case _:
            print("Iterable.")

wtp(3)  # Not an iterable.
wtp([])  # Iterable.

Another thing I learned from this article is the English noun chicanery, “the use of deception or subterfuge to achieve one's purpose”.

Previous link Next link

Number 73 is a number packed with interesting properties.

mathspp
  • Blog
    • Pydon'ts
    • Problems
    • TIL
    • Twitter threads
  • Books
  • Talks
  • Trainings
    • Advanced iteration
    • Python for scripting and automation
    • Rust for Python developers
  • Courses
  • About