Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(🎁) get_type_hints should add the class to the locals #1820

Closed
KotlinIsland opened this issue Jul 25, 2024 · 5 comments
Closed

(🎁) get_type_hints should add the class to the locals #1820

KotlinIsland opened this issue Jul 25, 2024 · 5 comments
Labels
topic: feature Discussions about new features for Python's type annotations

Comments

@KotlinIsland
Copy link

KotlinIsland commented Jul 25, 2024

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

@KotlinIsland KotlinIsland added the topic: feature Discussions about new features for Python's type annotations label Jul 25, 2024
@JelleZijlstra
Copy link
Member

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

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Jul 26, 2024
@KotlinIsland
Copy link
Author

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

@JelleZijlstra
Copy link
Member

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.

@KotlinIsland
Copy link
Author

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

@Viicos
Copy link
Contributor

Viicos commented Oct 11, 2024

@KotlinIsland I'll note that this isn't trivial. if Base and A were to be defined in a function, in which namespace should {cls.__name__: cls} be added?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: feature Discussions about new features for Python's type annotations
Projects
None yet
Development

No branches or pull requests

3 participants