6

I have this code to check for whether or not a variable is a number or a Vector2 in my Vector2 class when multiplying.

def __mul__(self, other):
    match type(other):
        case int | float:
            pass
        case Vector2:
            pass

If I run this, I get SyntaxError: name capture 'int' makes remaining patterns unreachable, and when I hover in vscode, it gives me:

"int" is not accessed
Irrefutable pattern allowed only as the last subpattern in an "or" pattern
All subpatterns within an "or" pattern must target the same names
Missing names: "float"
Irrefutable pattern is allowed only for the last case statement

If I remove | float it still won't work, so I can't make them separate cases.

1

1 Answer 1

10

Case with a variable (ex: case _: or case other:) needs to be the last case in the list. It matches any value, where the value was not matched by a previous case, and captures that value in the variable.

A type can be used in a case, but implies isinstance(), testing to determine if the value being matched is an instance of that type. Therefore, the value used for the match should be the actual variable other rather than the type type(other), since type(other) is a type whose type would match type().

def __mul__(self, other):
    match other:
        case int() | float():
            pass
        case Vector2():
            pass
1
  • This pattern is called a class pattern: "A class pattern provides support for destructuring arbitrary objects". More information can be found in the documentation: peps.python.org/pep-0622/#class-patterns
    – charelf
    Jan 16 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.