Python: match/case by type of value

Viewed 867

I came across a weird issue while using the new match/case syntax in Python3.10. The following example seems like it should work, but throws an error:

values = [
    1,
    "hello",
    True
]

for v in values:
    match type(v):
        case str:
            print("It is a string!")
        case int:
            print("It is an integer!")
        case bool:
            print("It is a boolean!")
        case _:
            print(f"It is a {type(v)}!")
$ python example.py
  File "/.../example.py", line 9
    case str:
         ^^^
SyntaxError: name capture 'str' makes remaining patterns unreachable
  • It is mentioning that the first case (the value str) will always result in True.

Wondering if there is an alternative to this other than converting the type to a string.

1 Answers

Rather than match type(v), match v directly:

values = [
    1,
    "hello",
    True,
]

for v in values:
    match v:
        case str():
            print("It is a string!")
        case bool():
            print("It is a boolean!")
        case int():
            print("It is an integer!")
        case _:
            print(f"It is a {type(v)}!")

Note that I've swapped the order of bool() and int() here, so that True being an instance of int doesn't cause issues.

Related