I am working on a system that lets you use a GUI to write some basic python to use as scripting in an application.
One of the things it does is let you set an attribute to some value, and I want to see if it can be handled by one of the type handlers that are implemented into the GUI. The native python typing module does not have a way to check if str
is a valid type for Optional[str]
or if int
is valid for Union[float, int, complex]
etc...
However, mypy does this type checking statically and has a function called is_subtype that I think would work great in this case; however, when I call it with python types, I get the exception TypeError: mypy.types.Type object expected; got type
, see the code below.
The mypy internals are pretty complicated, and I can't find a clear path from the python types to what mypy expects internally, is there an easy way to turn native python types into mypy types, or another function I should be using in mypy to check type compatibility at runtime?
from mypy.subtypes import is_subtype
is_subtype(float, int)
As user2357112 mentioned mypy is not designed for this. After speaking with someone very familiar with the internals, the best answer would be some version of evaling bits of code to AST then loading them into the bowels of mypy.
However pytypes is designed to provide this functionality and provides a function called is_subtype
some example use:
from pytypes import is_subtype
print(is_subtype(float, int))
# prints 'False'
print(is_subtype(float, Optional[float]))
# prints 'True'