This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: get_type_hints throws for nested class with __future__ annotations
Type: Stage: resolved
Components: Versions: Python 3.9
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: Nosy List: Prometheus3375, gvanrossum
Priority: normal Keywords:

Created on 2021-01-05 11:18 by Prometheus3375, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
annotations.py Prometheus3375, 2021-01-05 11:18 Quick representation of the problem
same_classes.py Prometheus3375, 2021-01-05 11:40 An example when a class and its module have classes with the same name
Messages (3)
msg384381 - (view) Author: Svyatoslav (Prometheus3375) * Date: 2021-01-05 11:18
If a class X has nested class Y and class X has annotation Y AFTER the definition of Y, get_type_hints(X) throws NameError if import from future annotations is present.

This is because get_type_hints looks only at mro of the class. Its namespace must be included too as locals.
msg384386 - (view) Author: Svyatoslav (Prometheus3375) * Date: 2021-01-05 11:40
>
This is because get_type_hints looks only at mro of the class. Its namespace must be included too as locals
<

I'll correct myself. get_type_hints() looks at all entites of mro of a class. If globals are not defined, globals of an entity module are used. But if locals are not defined, then no action is taken. Actually, class namespace must be used as locals in that case.

This is also supported by the case when a class and its module have classes with the same name. See same_classes.py for an example.
msg384423 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2021-01-05 18:41
If you want this to work you have to pass the namespace where B is defined as locals to get_type_hint(). The recommended approach is to make B a global class; where that is not possible (as in your second example) you should chose a different name.

We're not going to guess additional namespaces to add to the lookup, so I will close this as won't fix.

PS. For short code snippets like your examples, I prefer pasting the code inline.
History
Date User Action Args
2022-04-11 14:59:39adminsetgithub: 86995
2021-01-05 18:41:01gvanrossumsetstatus: open -> closed

nosy: + gvanrossum
messages: + msg384423

resolution: wont fix
stage: resolved
2021-01-05 11:40:50Prometheus3375setfiles: + same_classes.py

messages: + msg384386
2021-01-05 11:18:32Prometheus3375create