I\'m trying to write code that validates type hints, and in order to do so I have to find out what kind of object the annotation is. For example, consider this snippet that\
The most you could do, I think, is to use your typ
on a variable, use typing.get_type_hints
on it and extract the info you need from the returned __annotations__
-like dictionary.
PEP-484 says:
get_type_hints()
, a utility function to retrieve the type hints from a function or method. Given a function or method object, it returns a dict with the same format as__annotations__
, but evaluating forward references (which are given as string literals) as expressions in the context of the original function or method definition.
26.1.7. Classes, functions, and decorators says:
At runtime,
isinstance(x, T)
will raiseTypeError
. In general,isinstance()
andissubclass()
should not be used with types.
However, PEP-526 says in 'Non-goals':
While the proposal is accompanied by an extension of the
typing.get_type_hints
standard library function for runtime retrieval of annotations, variable annotations are not designed for runtime type checking. Third party packages will have to be developed to implement such functionality.