Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare types from Python typing

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?

like image 305
Mitar Avatar asked Jul 04 '26 23:07

Mitar


1 Answers

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 typing module will contain some building blocks for runtime type checking -- in particular the get_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.

like image 155
BoarGules Avatar answered Jul 07 '26 12:07

BoarGules



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!