Message388023
@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'>} |
|
Date |
User |
Action |
Args |
2021-03-03 14:41:54 | kj | set | recipients:
+ kj, eric.smith, 1ace |
2021-03-03 14:41:54 | kj | set | messageid: <1614782514.53.0.356595907008.issue43355@roundup.psfhosted.org> |
2021-03-03 14:41:54 | kj | link | issue43355 messages |
2021-03-03 14:41:54 | kj | create | |
|