Skip to content

Local vs global namespace to resolve forward annotations #8958

Answered by erictraut
Viicos asked this question in Q&A
Discussion options

You must be logged in to vote

Yeah, I don't think the typing spec provides much clarity on the intended behavior here. We should perhaps address this.

In cases like this, I look to the runtime behavior for clues about the correct behavior. In this case, pyright attempts to match the observed runtime behavior of typing.get_type_hints. For details, refer to PEP 563.

from typing import TypeAlias, get_type_hints

MyType: TypeAlias = int

class Class:
    MyType: TypeAlias = str

    forward: "MyType"
    not_forward: MyType

print(get_type_hints(Class))  # forward: int, not_forward: str

The behavior (non-intuitively) changes if you move the type alias definition to the bottom of the class.

from typing import TypeAlias, ge…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@Viicos
Comment options

@carljm
Comment options

@erictraut
Comment options

@Viicos
Comment options

Answer selected by Viicos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants