I am reading the typing code of the module, as well as looking at mypy to understand how it performs type checking. Unfortunately for me, mypy creates a very smart tree with typed expressions that I still don't understand, and all this is based on static analysis.
I would like to implement a type checking system that is dynamic (without static analysis) in Python. Assuming the type checking function is called check_type , I want to do the following:
>>> import typing >>> >>> check_type(1, int) True >>> check_type(1, float) False >>> check_type([1], typing.List[int]) True >>> check_type([1], typing.List[float]) False >>> check_type([1], typing.List[typing.Any]) True >>> check_type((1,), typing.Tuple[int]) True
I was thinking of recreating an object type from its value, for example:
>>> get_type([1]) typing.List<~T>[int]
But this does not work with issubclass :
>>> issubclass(typing.List[int], typing.List[typing.Any]) False
I donβt see an easy way to check types in Python without taking a lot of things about the internal elements of the typing stdlib module (e.g. access to __args__ or __tuple_params__ ).
How can I correctly implement the check_type function, which works for the cases listed above? I am using Python 2.7.
source share