-
Consider the following example: Code sample in pyright playground from typing import TypeAlias, reveal_type
MyType: TypeAlias = int
class Class:
MyType: TypeAlias = str
forward: 'MyType'
not_forward: MyType
reveal_type(Class().forward) # int
reveal_type(Class().not_forward) # str I've tried looking into the typing spec and could only find an example related to method arguments, but I believe it should work the same:
(emphasis mine). mypy seems to infer Is this expected behavior? If not, should we also update/clarify the typing specification? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
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 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, get_type_hints
MyType: TypeAlias = int
class Class:
forward: "MyType"
not_forward: MyType
MyType: TypeAlias = str
print(get_type_hints(Class)) # forward: int, not_forward: int For reference, here's the original pyright bug report that prompted me to change its behavior to match that of |
Beta Was this translation helpful? Give feedback.
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.The behavior (non-intuitively) changes if you move the type alias definition to the bottom of the class.