2

I would like to write a pattern matching block that detects whether the object being matched is the type/class object, for example, int or str. Not an instance of these, but the actual class object int or str.

This is a SyntaxError:

x = int

match x:
    case str:
        print("x is str")
    case int:
        print("x is int")

How to do it?

UPDATE, the following does NOT work, but the SyntaxError is at least solved:

x = int

match [x]:
    case [str]:
        print("x is str")
    case [int]:
        print("x is int")

(Incorrect result: x is str)

UPDATE: the problem is that the bare int or str is a capture pattern and note a value pattern. The name int or str would be BOUND with a naked case int: or case str:. You have to use something wit dot notation to make it not capture.

This works:

import builtins

x = int

match x:
    case builtins.str:
        print("x is str")
    case builtins.int:
        print("x is int")

For a non-builtin, you must do something like:

import mymodule

x = mymodule.MyClass

match x:
    case mymodule.MyClass:
        print("x is MyClass")
    case mymodule.MyOtherClass:
        print("x is MyOtherClass")
Rick
  • 43,029
  • 15
  • 76
  • 119

0 Answers0