[New-bugs-announce] [issue45091] inspect.Parameter.__str__ does not include subscripted types in annotations

Antonio Caceres report at bugs.python.org
Thu Sep 2 21:25:32 EDT 2021


New submission from Antonio Caceres <contact at antonio-caceres.com>:

The __str__ method of the inspect.Parameter class in the standard library's inspect module does not include subscripted types in annotations.

For example, consider the function foo(a: list[int]).
When I run str(inspect.signature(foo)), I would expect the returned string to be '(a: list[int])', but instead the string is '(a: list)'.

(I have tested this on Python 3.9.7, but the code I believe is the problem is on the branches for versions 3.9-3.11.) 

>From a first glance at the source code, the problem is in the inspect.formatannotation function. If the annotation is a type, the formatannotation uses the __qualname__ attribute of the annotation instead of its __repr__ attribute. Indeed, list[int].__qualname__ == 'list' and repr(list[int]) == 'list[int]'. This problem was probably code that should have been changed, but never was, after PEP 585.

The only workarounds I have found is to implement an alternative string method that accepts inspect.Signature or subclass inspect.Parameter and override the __str__ method.

----------
components: Library (Lib)
messages: 400972
nosy: antonio-caceres
priority: normal
severity: normal
status: open
title: inspect.Parameter.__str__ does not include subscripted types in annotations
type: behavior
versions: Python 3.10, Python 3.11, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45091>
_______________________________________


More information about the New-bugs-announce mailing list