I am reading the typing module code and also looking into mypy to understand how it does type checking. Unfortunately for me, mypy builds a very smart tree with typed expressions that I still don't understand, and it's all based on static analysis.
I would like to implement a type check system that is dynamic (no static analysis) in Python. Assuming the function that performs type checks is called check_type, I want to accomplish 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 thought about recreating the object type from its value, such as:
>>> get_type([1]) typing.List<~T>[int] But this doesn't work with issubclass:
>>> issubclass(typing.List[int], typing.List[typing.Any]) False I don't see a simple way to check types in Python without assuming a lot of things about the internals of the typing stdlib module (e.g., accessing __args__ or __tuple_params__).
How can I properly implement a check_type function that work for the cases previously listed? I am using Python 2.7.
isinstance?isinstancedoesn't check the type completely. For example:isinstance(['string'], typing.List[int]) is Truewhen that's not exactly what I am looking for.try/exceptstatement and treat the value you want to test as the value you expect and if aTypeErrorexception is raised do something else or just pass