When inspecting at runtime the annotations of a function, one can get the class annotated for a given argument. For example:
>>> import inspect
>>> inspect.signature(f).parameters['a'].annotation
<class 'int'>
The same can be achieved by doing f.__annotations__.
However, for reasons I will spare the reader, I would like to get the annotation in readable text format. For example: a: int will be retrieved as int, not as <class 'int'>. Assume the text should be legal as input to eval.
I know I can do:
>>> str(inspect.signature(f).parameters['a'])
'a:int'
And then process this string using .split and such. But I'm wondering if there's a better way.
Aucun commentaire:
Enregistrer un commentaire