[Python] Using pattern matching with a class that inherits from str in Python 3.10

Discussão em 'Python' iniciado por Stack, Junho 14, 2025.

  1. Stack

    Stack Membro Participativo

    In a parser library I maintain, I have some classes that inherit from str to manage parsed strings and parsed symbols. This has been working well for a long time, but with Python 3.10, someone requested being able to use match and case on these classes. I have constructed an example script that shows how this is failing:

    class Binge(str):
    def __eq__(self, other):
    return self.__class__ == other.__class__ and str.__eq__(self, other)

    def __ne__(self, other):
    return not self == other


    # These two asserts are important for how the class is used
    assert Binge('a') == Binge('a')
    assert Binge('a') != 'a'

    # What does it take to then make this work?
    matched = False
    match Binge("asdf"):
    case Binge("asdf"):
    matched = True
    assert matched


    If I add:

    print(self.__class__, other.__class__)


    in the __eq__ function, I see this:

    <class '__main__.Binge'> <class 'str'>

    Continue reading...

Compartilhe esta Página