python/typing

(๐ŸŽ) `get_type_hints` should add the class to the locals

KotlinIsland opened this issue ยท 5 comments

from __future__ import annotations

from typing import get_type_hints


class Base:
    def __init_subclass__(cls, **kwargs):
        get_type_hints(cls)


class A(Base):
    a: A | None
...
NameError: name 'A' is not defined

raised here: KotlinIsland/basedtyping#117

At the time the class is being created, A is not bound yet. This is correct behavior and will not change.

surely you could do something as simple as:

from __future__ import annotations

from typing import get_type_hints


class Base:
    def __init_subclass__(cls, **kwargs):
        get_type_hints(cls, globalns={cls.__name__: cls})


class A(Base):
    a: A | None

You could do that when you call get_type_hints(); Python should not.

In Python 3.14 you can call get_type_hints() with the FORWARDREF format to prevent a NameError.

why should the get_type_hints function not do this behaviour? if the class has already been defined, but not yet added to the namespace, why can't we just add it? the function already has special cased behaviour to accumulate all of the base namespaces together