Reputation: 91
Consider the following python file test.py
:
def accepts_string(s: str):
pass
If I open a python shell, import this function and then grab the function's parameter s
and its annotation I get a string literal.
>>> import inspect
>>> from test import accepts_string
>>> inspect.signature(accepts_string).parameters['s'].annotation
'str'
However, if I define the function in the shell - I get the expected results of an actual "class type".
>>> import inspect
>>> def accepts_string(s: str):
... pass
...
>>> inspect.signature(accepts_string).parameters['s'].annotation
<class 'str'>
I would expect to always get the later results and I'm having trouble reconciling the different results based on whether the function is imported vs. defined live.
Upvotes: 3
Views: 1500
Reputation: 91
This issue was due to a lack of understanding what from __future__ import annotations
was doing. This was included at the top of my file and was omitted from the initial example I gave. Apologies for not realizing that when making this post.
As a user pointed out in the comments:
The future behavior will become the default behavior, it was supposed to in Python 3.10, but it got delayed, not sure the current status
I think I will need to use typing.get_type_hints
anyway to reliably grab annotations for functions for future python versions.
Upvotes: 3