[issue43817] Add inspect.get_annotations()

Guido van Rossum report at bugs.python.org
Mon Apr 26 20:38:13 EDT 2021


Guido van Rossum <guido at python.org> added the comment:

I want to be as short as possible.

The user may have annotations because they are using mypy. They may be
using a library that calls inspect.signature() on some of their functions
to retrieve the parameter names conveniently.

All this has worked for years, the library never caring about annotations,
the user probably adding a few more annotations as they get more value out
of mypy.

Now one day, using Python 3.9, the user adds "from __future__ import
annotations" to their module, and removes the quotes from annotations
containing forward references or things imported under "if TYPE_CHECKING".

This works in 3.9. But you want to break it in 3.10. This is what I object
to.

I realize this also broke in the 3.10 alphas where PEP 563 was the default.
But that was rolled back for a reason! And we changed inspect.signature()
to call get_type_hints() (i.e. call eval() and break if it fails) because
it wasn't just affecting users PEP 563, it was affecting everyone who *was*
expecting a type object rather than a string in Parameter.annotation. That
bug also exists in 3.9, but only for users of PEP 563 (most of whom didn't
care about runtime inspection of annotations, so it didn't matter to them
that Parameter.annotation got a string.

You can draw the matrix of use cases and Python versions yourself.

Given that we're not going whole-hog on PEP 563 in 3.10, I think we should
either leave sleeping dogs lie, and continue to return a string as
Parameter.annotation if PEP 563 was in effect, or else we should at least
make inspect.signature() not fail if the string fails to evaluate. Note
that the version of inspect.signature() that I remember being checked into
3.10 did catch exceptions from get_type_hints() and used the original
__annotations__ dict (i.e. with all strings) if there was an eval error (or
any other error, IIRC). Please go look for it if you don't believe me (it
would have been rolled back last week in the Great Rollback).

----------

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


More information about the Python-bugs-list mailing list