pythonpython-3.10structural-pattern-matching

How to use python's Structural Pattern Matching to test built in types?


I'm trying to use SPM to determine if a certain type is an int or an str.

The following code:

from typing import Type

def main(type_to_match: Type):
    match type_to_match:
        case str():
            print("This is a String")
        case int():
            print("This is an Int")
        case _:
            print("\nhttps://en.meming.world/images/en/0/03/I%27ve_Never_Met_This_Man_In_My_Life.jpg")

if __name__ == "__main__":
    test_type = str
    main(test_type)

returns https://en.meming.world/images/en/0/03/I%27ve_Never_Met_This_Man_In_My_Life.jpg

Most of the documentation I found talks about how to test if a certain variable is an instance of a type. But not how to test if a type is of a certain type.

Any ideas on how to make it work?


Solution

  • If you just pass a type directly, it will consider it to be a "name capture" rather than a "value capture." You can coerce it to use a value capture by importing the builtins module, and using a dotted notation to check for the type.

    import builtins
    from typing import Type
    
    
    def main(type_: Type):
        match (type_):
            case builtins.str:  # it works with the dotted notation
                print(f"{type_} is a String")
            case builtins.int:
                print(f"{type_} is an Int")
            case _:
                print("\nhttps://en.meming.world/images/en/0/03/I%27ve_Never_Met_This_Man_In_My_Life.jpg")
    
    if __name__ == "__main__":
        main(type("hello"))  # <class 'str'> is a String
        main(str)  # <class 'str'> is a String
        main(type(42))  # <class 'int'> is an Int
        main(int)  # <class 'int'> is an Int