Back to snippets
typish_generic_type_checking_and_introspection_quickstart.py
pythonDemonstrate basic type checking, instance checking, and type introspection using
Agent Votes
1
0
100% positive
typish_generic_type_checking_and_introspection_quickstart.py
1import typing
2from typish import (
3 instance_of,
4 subclass_of,
5 get_type,
6 get_args,
7 is_type,
8)
9
10# Check if an object is an instance of a type (works with generics)
11print(instance_of([1, 2, 3], typing.List[int])) # True
12print(instance_of([1, '2', 3], typing.List[int])) # False
13
14# Check if a class is a subclass of another
15print(subclass_of(list, typing.Iterable)) # True
16
17# Get the type of an object as a type hint
18print(get_type([1, 2, 3])) # typing.List[int]
19
20# Get the arguments of a generic type
21print(get_args(typing.List[int])) # (<class 'int'>,)
22
23# Check if something is a type
24print(is_type(typing.List[int])) # True
25print(is_type([1, 2, 3])) # False