Casting an attribute #9581
-
from typing import Any, cast, reveal_type
class C:
a: dict[int, int] | None = None
c = C()
c.a = cast(dict[int, Any], c.a)
reveal_type(c.a) # Type of "c.a" is "dict[int, int]" What can a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
A When you assign a value of type |
Beta Was this translation helpful? Give feedback.
A
cast
doesn't affect assignment. The subexpressioncast(dict[int, Any], c.a)
simply tells a type checker to ignore the type it normally evaluates for thec.a
and replace that type withdict[int, Any]
.When you assign a value of type
dict[int, Any]
(whether that comes from normal type evaluation or acast
) to an attribute whose type is declared asdict[int, int] | None
, the assignment is allowed becausedict[int, Any]
is assignable todict[int, int] | None
. Type narrowing is applied on assignment. The typedict[int, int] | None
is narrowed todict[int, int]
in this case. Thereveal_type
call displays the locally-narrowed type at that location within the program.