Crimes with Python's Pattern Matching (2022)

104 agluszak 38 8/21/2025, 7:47:02 PM hillelwayne.com ↗

Comments (38)

pansa2 · 2h ago
The real crime is the design of Python's pattern matching in the first place:

    match status:
        case 404:
            return "Not found"

    not_found = 404
    match status:
        case not_found:
            return "Not found"
Everywhere else in the language, you can give a constant a name without changing the code's behaviour. But in this case, the two snippets are very different: the first checks for equality (`status == 404`) and the second performs an assignment (`not_found = status`).

https://x.com/brandon_rhodes/status/1360226108399099909

user453 · 42m ago
That's destructuring, a feature not a bug. Same as it works in any functional language - and tremendously useful once you get the hang of it
pansa2 · 35m ago
At least functional languages tend to have block scope, so the latter snippet introduces a new variable that shadows `not_found` instead of mutating it.
quotemstr · 17m ago
Destructuring is a feature. Making the difference between value capture and value reference subtle and unintuitive was a design error in pattern matching. When combined with Python having a flat locals scope, it became a calamity.
quotemstr · 1h ago
And there was a much better proposal that got rejected in favor of what we got: https://peps.python.org/pep-0642/
danudey · 1h ago
The very first example there shows a match/case block where almost every single case just runs "pass" and yet every single one has a side effect. It's very difficult to read at first, difficult to understand if you're new to the syntax, and is built entirely around side effects. This might be one of the worst PEPs I've ever seen just based on that example alone.

Fun fact: you can do the same thing with the current match/case, except that you have to put your logic in the body of the case so that it's obvious what's happening.

almostgotcaught · 57m ago
because it's not a `switch` it's a `match` ie pattern matching...
pansa2 · 38m ago
Doesn't matter what it is, it shouldn't break fundamental rules of the language.

Ruby's `case`/`in` has the same problem.

almostgotcaught · 23m ago
> it shouldn't break fundamental rules of the language

it doesn't? you simply don't understand what a match statement is.

https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html

    let num = Some(4);

    match num {
        Some(x) if x % 2 == 0 => println!("The number {x} is even"),
        Some(x) => println!("The number {x} is odd"),
        None => (),
    }
notice that x is bound to 4.
pansa2 · 6m ago
> you simply don't understand what a match statement is

It's "a DSL contrived to look like Python, and to be used inside of Python, but with very different semantics":

https://discuss.python.org/t/gauging-sentiment-on-pattern-ma...

purplehat_ · 2h ago
Could someone explain just what's so bad about this?

My best guess is that it adds complexity and makes code harder to read in a goto-style way where you can't reason locally about local things, but it feels like the author has a much more negative view ("crimes", "god no", "dark beating heart", the elmo gif).

xg15 · 1h ago
Maybe I have too much of a "strongly typed language" view here, but I understood the utility of isinstance() as verifying that an object is, well, an instance of that class - so that subsequent code can safely interact with that object, call class-specific methods, rely on class-specific invariants, etc.

This also makes life directly easier for me as a programmer, because I know in what code files I have to look to understand the behavior of that object.

Even linters use it to that purpose, e.g. resolving call sites by looking at the last isinstance() statement to determine the type.

__subclasshook__ puts this at risk by letting a class lie about its instances.

As an example, consider this class:

  class Everything(ABC):

    @classmethod
    def __subclasshook__(cls, C):
      return True

    def foo(self):
      ...
You can now write code like this:

  if isinstance(x, Everything):
    x.foo()
A linter would pass this code without warnings, because it assumes that the if block is only entered if x is in fact an instance of Everything and therefore has the foo() method.

But what really happens is that the block is entered for any kind of object, and objects that don't happen to have a foo() method will throw an exception.

taeric · 1h ago
I took the memes as largely for comedic effect, only?

I do think there is a ton of indirection going on in the code that I would not immediately think to look for. As the post stated, could be a good reason for this in some things. But it would be the opposite of aiming for boring code, at that point.

gnulinux · 1h ago
Side effects
danudey · 1h ago
TL;DR having a class that determines if some other class is a subclass of itself based off of arbitrary logic and then using that arbitrary logic to categorize other people's arbitrary classes at runtime is sociopathic.

Some of these examples are similar in effect to what you might do in other languages, where you define an 'interface' and then you check to see if this class follows that interface. For example, you could define an interface DistancePoint which has the fields x and y and a distance() method, and then say "If this object implements this interface, then go ahead and do X".

Other examples, though, are more along the lines of if you implemented an interface but instead of the interface constraints being 'this class has this method' the interface constraints are 'today is Tuesday'. That's an asinine concept, which is what makes this crimes and also hilarious.

charlieyu1 · 1h ago
More and more dubious things were designed in Python these days. A recent PEP purposes to use {/} as the empty set
umgefahren · 1h ago
Idk that doesn’t sound so dubious to me. ∅ might be more approachable for the PHDs then set() ;)
rtrgrd · 38m ago
we all love non ascii code (cough emoji variable names)
augusto-moura · 53m ago
Problem is, we already have a syntax for empty lists [], empty tuples (), and {} is taken for an empty dict. So having a syntax for an empty set actually makes sense to me
kurtis_reed · 48m ago
{:} should have been the empty dict, now there's no good solution
augusto-moura · 26m ago
I agree that {:} would be a better empty expression for dicts, but that ship has already sailed. {/} looks like a good enough alternative
vlade11115 · 2h ago
While the article is very entertaining, I'm not a fan of the pattern matching in Python. I wish for some linter rule that can forbid the usage of pattern matching.
siddboots · 2h ago
Can you explain why? Genuinely curious as a lover of case/match. My only complaint is that it is not general enough.
kurtis_reed · 1h ago
Double indentation
jbmchuck · 2h ago
Should be easily doable with a semgrep rule, e.g.:

    ~> cat semgrep.yaml
    rules:
      - id: no-pattern-matching
        pattern: |
          match ...:
        message: |
          I'm not a fan of the pattern matching in Python
        severity: ERROR
        languages:
          - python
...

    ~> cat test.py
    #!/usr/bin/env python3

    foo = 1
    match foo:
      case 1:
        print("one")
...

    ~> semgrep --config semgrep.yaml test.py   


     no-pattern-matching
          I'm not a fan of the pattern matching in Python
                                                         
            4┆ match foo:
            5┆   case 1:
            6┆     print("one")
(exits non-0)
smcl · 2h ago
If you're experienced enough with Python to say "I want to eliminate pattern matching from my codebase" you can surely construct that as a pre-commit check, no?
Y_Y · 1h ago
Barely a misdemeanor, all of the typechecks were deterministic
danudey · 1h ago
Next step is to have the subclass check pack all the code up, send it to ChatGPT, ask it if it thinks subjectively that class A should be a subclass of class B, and then run sentiment analysis on the resulting text to make the determination.
quotemstr · 4h ago
I've never understood why Python's pattern-matching isn't more general.

First, "case foo.bar" is a value match, but "case foo" is a name capture. Python could have defined "case .foo" to mean "look up foo as a variable the normal way" with zero ambiguity, but chose not to.

Second, there's no need to special-case some builtin types as matching whole values. You can write "case float(m): print(m)" and print the float that matched, but you can't write "case MyObject(obj): print(obj)" and print your object. Python could allow "..." or "None" or something in __match_args__ to mean "the whole object", but didn't.

rpcope1 · 3h ago
After doing Erlang and Scala pattern matching, the whole Python implementation just feels really ugly and gross. They should have cribbed a lot more of how Scala does it.
orbisvicis · 2h ago
I've given up on matching as I'm tired of running into its limitations.

That said, I don't think OP's antics are a crime. That SyntaxError though, that might be a crime.

And a class-generating callable class would get around Python caching the results of __subclasshook__.

Aefiam · 3h ago
case .foo is explicitly mentioned in https://peps.python.org/pep-0622/ :

> While potentially useful, it introduces strange-looking new syntax without making the pattern syntax any more expressive. Indeed, named constants can be made to work with the existing rules by converting them to Enum types, or enclosing them in their own namespace (considered by the authors to be one honking great idea)[...] If needed, the leading-dot rule (or a similar variant) could be added back later with no backward-compatibility issues.

second: you can use case MyObject() as obj: print(obj)

zahlman · 3h ago
I don't think I've written a match-case yet. Aside from not having a lot of use cases for it personally, I find that it's very strange-feeling syntax. It tries too hard to look right, with the consequence that it's sometimes quite hard to reason about.
quotemstr · 2h ago
> > While potentially useful, it introduces strange-looking new syntax without making the pattern syntax any more expressive. Indeed, named constants can be made to work with the existing rules by converting them to Enum types, or enclosing them in their own namespace (considered by the authors to be one honking great idea)[...]

Yeah, and I don't buy that for a microsecond.

A leading dot is not "strange" syntax: it mirrors relative imports. There's no workaround because it lets you use variables the same way you use them in any other part of the language. Having to distort your program by adding namespaces that exist only to work around an artificial pattern matching limitation is a bug, not a feature.

Also, it takes a lot of chutzpah for this PEP author to call a leading dot strange when his match/case introduces something that looks lexically like constructor invocation but is anything but.

The "as" thing works with primitive too, so why do we need int(m)? Either get rid of the syntax or make it general. Don't hard-code support for half a dozen stdlib types for some reason and make it impossible for user code to do the equivalent.

The Python pattern matching API is full of most stdlib antipatterns:

* It's irregular: matching prohibits things that the shape of the feature would suggest are possible because the PEP authors couldn't personally see a specific use case for those things. (What's the deal with prohibiting multiple _ but allowing as many __ as you want?)

* It privileges stdlib, as I mentioned above. Language features should not grant the standard library powers it doesn't extend to user code.

* The syntax feels bolted on. I get trying to reduce parser complexity and tool breakage by making pattern matching look like object construction, but it isn't, and the false cognate thing confuses every single person who tries to read a Python program. They could have used := or some other new syntax, but didn't, probably because of the need to build "consensus"

* The whole damn thing should have been an expression, like the if/then/else ternary, not a statement useless outside many lexical contexts in which one might want to make a decision. Why is it a statement? Probably because the PEP author didn't _personally_ have a need to pattern match in expression context.

And look: you can justify any of these technical decisions. You can a way to justify anything you might want to do. The end result, however, is a language facility that feels more cumbersome than it should and is applicable to fewer places than one might think.

Here's how to do it right: https://www.gnu.org/software/emacs/manual/html_node/elisp/pc...

> If needed, the leading-dot rule (or a similar variant) could be added back later with no backward-compatibility issues.

So what, after another decade of debate, consensus, and compromise, we'll end up with a .-prefix-rule but one that works only if the character after the dot is a lowercase letter that isn't a vowel.

PEP: "We decided not to do this because inspection of real-life potential use cases showed that in vast majority of cases destructuring is related to an if condition. Also many of those are grouped in a series of exclusive choices."

I find this philosophical stance off-putting. It's a good thing when users find ways to use your tools in ways you didn't imagine.

PEP: In most other languages pattern matching is represented by an expression, not statement. But making it an expression would be inconsistent with other syntactic choices in Python. All decision making logic is expressed almost exclusively in statements, so we decided to not deviate from this.

We've had conditional expressions for a long time.

depressedpanda · 11m ago
Agreed.

After starting my new job and coming back to Python after many years I was happy to see that they had added `match` to the language. Then I was immediately disappointed as soon as I started using it as I ran into its weird limitations and quirks.

Why did they design it so poorly? The language would be better off without it in its current hamstrung form, as it only adds to the already complex syntax of the language.

> PEP: In most other languages pattern matching is represented by an expression, not statement. But making it an expression would be inconsistent with other syntactic choices in Python. All decision making logic is expressed almost exclusively in statements, so we decided to not deviate from this.

> We've had conditional expressions for a long time.

Also, maybe most other languages represent it as an expression because it's the sane thing to do? Python doing its own thing here isn't the win they think it is.

Jtsummers · 2h ago
> (What's the deal with prohibiting multiple _ but allowing as many __ as you want?)

What do you mean "prohibiting multiple _"? As in this pattern:

  match [1,2]:
    case [_, _]: print("A list of two items")
That works fine.
quotemstr · 2h ago
> An irrefutable case block is a match-all case block. A match statement may have at most one irrefutable case block, and it must be last.

There is no reason to have this restriction except that some people as a matter of opinion think unreachable code is bad taste and the language grammar should make bad taste impossible to express. It's often useful to introduce such things as a temporary state during editing. For example,

    def foo(x):
        match x:
            case _:
                log.warning("XXX disabled for debugging")
                return PLACEHOLDER
            case int():
                return bar()
            case str():
                return qux()
            case _:
                return "default"
Why should my temporary match-all be a SyntaxError???? Maybe it's a bug. Maybe my tools should warn me about it. But the language itself shouldn't enforce restrictions rooted in good taste instead of technical necessity.

I can, however, write this:

    def foo(x):
        match x:
            case _ if True:
                log.warning("XXX disabled for debugging")
                return PLACEHOLDER
            case int():
                return bar()
            case str():
                return qux()
            case _:
                return "default"
Adding a dummy guard is a ridiculous workaround for a problem that shouldn't exist in the first place.
Jtsummers · 1h ago
I don't disagree, it should be a warning but not an error. Thanks for clarifying, your original remark was ambiguous there.