As I noticed today, the Python 3.10 inspect module now uses typing.get_type_hints ()
to interpret types. The corresponding commit is hereis.
This seems to be a fix related to lazy evaluation of annotations, which is enabled by default from Python 3.10. Since the type annotation information packed in ʻobj.annotationsbecomes a character string, it may be judged that it is appropriate to leave it to
typing.get_type_hints (). With this change, the type information of ʻinspect.signature ()
, which simply referred to ʻobj.annotations`, is switched to the analysis result that goes one step further.
For example, Python 3.9 treats the following hello ()
function argument name
as a str
type.
$ python3.9
Python 3.9.0 (default, Oct 24 2020, 15:41:29)
[Clang 11.0.3 (clang-1103.0.32.59)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def hello(name: str = None):
... print("Hello ", name)
...
>>> import inspect
>>> inspect.signature(hello)
<Signature (name: str = None)>
On the other hand, in Python 3.10 (under development) it is considered to be of type ʻOptional [str]. Seeing that the default argument is
None`, it returns a better type.
$ python3.10
Python 3.10.0a1+ (heads/master:805ef73, Oct 24 2020, 15:07:19)
[Clang 11.0.3 (clang-1103.0.32.59)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def hello(name: str = None):
... print("Hello ", name)
...
>>> import inspect
>>> inspect.signature(hello)
<Signature (name: Optional[str] = None)>
By the way, if the name cannot be resolved at runtime (such as when typing.TYPE_CHECKING
is not imported at runtime), ʻobj.__ signature__` is still referenced, so the interpretation result may change depending on the annotation.
$ python3.10
Python 3.10.0a1+ (heads/master:805ef73, Oct 24 2020, 15:07:19)
[Clang 11.0.3 (clang-1103.0.32.59)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def hello(name: Unknown, age: int = None): pass
...
>>> import inspect
>>> inspect.signature(hello)
<Signature (name: 'Unknown', age: 'int' = None)>
In this case, the ʻUnknown type cannot be resolved, so the type of the argument ʻage
is not ʻOptional [int], but just ʻint
.
Recommended Posts