Reputation: 990
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)
Upvotes: 2
Views: 659
Reputation: 990
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 functanility 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'
Upvotes: 1
Reputation: 280181
mypy isn't designed to be used as an imported library. The only supported use is through its command-line interface (running it directly or as a daemon). There is no support for what you're trying to do.
mypy's notion of "type" or "subtype" is one that only makes sense during static analysis, not at runtime. mypy's notion of a type works in terms of source code and parse information, and is completely separate from any runtime objects used to represent types. It is not even generally possible to determine what type mypy would have seen, given a runtime object representing a type. For example, NewType
objects don't hold enough information to reconstruct their original source location, and type variables mean different things in different contexts in a way that cannot be reconstructed at runtime.
Even if you manage to dig up enough implementation details to get this close to working, it may all break with the next update, as there are no backward compatibility guarantees for such unsupported use of mypy internals.
Upvotes: 2