Sadly this won't work, because the annotations are "evaluated" (or not) in the surrounding scope, not in the function's scope. Example:
>>> def f(a: int):
...   class C: pass
...   def g(b: C): pass
...   return g
>>> g = f(1)
>>> g.__annotations__
{'b': 'C'}
>>> g.__closure__
Here we want to know what the 'C' refers to in g's annotations. But g's closures are no help (unless g's body were to also reference C, which is not likely in typical code).


On Tue, Feb 2, 2021 at 6:10 PM Caleb Donovick <> wrote:
The discussion around PEP 649 got me thinking about what I believe is the largest downside to PEP 563: the inability to evaluate annotations created with closures.  While this is in general unavoidable,  if the type is ever referenced in an annotated function (including as an annotation) it should be resolvable via `__closure__`.  

For example:
from __future__ import annotations
import typing
def gen(T):
    def f(x: T):
        y: T = ... 
    return f

f = gen(int)
nonlocal_vars = {
  var : cell.cell_contents
  for var, cell in zip(f.__code__.co_freevars, f.__closure__)
assert typing.get_type_hints(f, localns=nonlocal_vars)  == {'x': int}

I would just open a PR to have `get_type_hints` attempt to resolve closure variables by default.  However, this would require an update to PEP 563 and I don't know what the protocol is there.

-  Caleb Donovick
Python-Dev mailing list --
To unsubscribe send an email to
Message archived at
Code of Conduct:

--Guido van Rossum (
Pronouns: he/him (why is my pronoun here?)