Finding edge cases for PEPs 484, 563, and 649 (type annotations)

I know this is old, but I think it’s still worth adding one more case (after a quick search I think this is new here).

See Is there a way to access parent nested namespaces? - #4 by dwreeves by @dwreeves.

Using from __future__ import annotations changes the reference count on a type annotation, and so makes some code that is valid before PEP 563, impossible after.

For example:

# from __future__ import annotations
import gc

def nested1():
    Bar = 'this is Bar'

    def nested2():
        class MyClass:
            bar: Bar
        return MyClass

    print('Total scopes referencing Bar:', len(gc.get_referrers(Bar)))
    return nested2

nested1()()

I get: Total scopes referencing Bar: 3 printed, but if I uncomment from __future__ import annotations, I get Total scopes referencing Bar: 1.

In other words having the Bar annotation as a python object keeps Bar from being GCed.

It seems this case is impossible to work around with PEP 563.