'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 1:[1]
As its name suggests, structural pattern matching is more suited for matching patterns, not values (like a classic switch/case in other languages). For example, it makes it very easy to check different possible structures of a list or a dict, but for values there is not much advantage over a simple if/else structure:
if type_to_match == str:
print("This is a String")
elif type_to_match == int:
print("This is an Int")
else:
print("\nhttps://en.meming.world/images/en/0/03/I%27ve_Never_Met_This_Man_In_My_Life.jpg")
But if you really want to use SPM, you could use the guard feature along with issublcass to check if a type is or is a child of any other:
match type_to_match:
case s if issubclass(type_to_match, str):
print(f"{s} - This is a String")
case n if issubclass(type_to_match, int):
print(f"{n} - This is an Int")
case _:
print("\nhttps://en.meming.world/images/en/0/03/I%27ve_Never_Met_This_Man_In_My_Life.jpg")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
