Search code examples
pythonoperator-overloadingstructural-pattern-matching

Can you overload the match operator?


There are many operators in python that can be overloaded (like +). But going through the docs for python 3.10 and PEP 622, I was wondering whether the same can be done for the match operator (e.g. to simplify an object's representation) - or would this be done through the __match_args__ attribute?


Solution

  • Can you overload the match operator?

    The short answer is No.

    The logic for Structural Pattern Matching is hardwired into the grammar of the language. The only method hook is __match_args__ which is only used to give field names for positional arguments in the class pattern.