I have a function accepting another Python functions which are annotated with type hints (__annotations__). I would like to use those hints to do some type checking during runtime. The issue is that type classes from typing module does not seem very easy to work with (no isinstance, no issubclass). So, I wonder, is there a way to convert them to mypy type objects, and then use mypy.subtypes.is_subtype to compare types from type hints?
The short answer is there is no easy way. The typing module is, by design, not going to provide much help for runtime checking. PEP 484 says
This PEP aims to provide a standard syntax for type annotations, opening up Python code to easier static analysis and refactoring, potential runtime type checking, and (perhaps, in some contexts) code generation utilizing type information.
Of these goals, static analysis is the most important. This includes support for off-line type checkers such as
mypy, as well as providing a standard notation that can be used by IDEs for code completion and refactoring.Non-goals
While the proposed
typingmodule will contain some building blocks for runtime type checking -- in particular theget_type_hints()function -- third party packages would have to be developed to implement specific runtime type checking functionality, for example using decorators or metaclasses. Using type hints for performance optimizations is left as an exercise for the reader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With