Ken Jin <kenjin4...@gmail.com> added the comment:

@eric.smith, here's a summarized version. I hope it helps:

def foo(x: str) -> str: ...

In Python 3.7 - 3.9 with from __future__ import annotations, inspect.signature 
sees foo's parameter as:

<Parameter "x: 'str'">

Without the future import (and also in Python 3.10):

<Parameter "x: str">

The reason for the difference in 3.10 (IIRC) is that inspect.signature auto 
converts all strings to typing.ForwardRef internally and then resolves them. 
This is a result of PEP 563 becoming default (also mentioned here 
https://docs.python.org/3.10/whatsnew/3.10.html#pep-563-postponed-evaluation-of-annotations-becomes-default
 )

Prior to 3.10, the future import treats function annotations as strings and 
inspect.signature _doesn't_ convert them. I don't know of this is a bug or 
intentional. Especially considering what PEP 563 has to say: 
https://www.python.org/dev/peps/pep-0563/#resolving-type-hints-at-runtime

@1ace, a possible workaround if you want full compatibility regardless of the 
future import is to use typing.get_type_hints:

(The result doesn't change even with from __future__ import annotations. This 
also works from 3.7-3.10)
>>> from typing import get_type_hints
>>> get_type_hints(foo)
{'x': <class 'str'>, 'return': <class 'str'>}

----------
nosy: +kj

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue43355>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to