Skip to content

Casting an attribute #9581

Answered by erictraut
amacfie-tc asked this question in Q&A
Discussion options

You must be logged in to vote

A cast doesn't affect assignment. The subexpression cast(dict[int, Any], c.a) simply tells a type checker to ignore the type it normally evaluates for the c.a and replace that type with dict[int, Any].

When you assign a value of type dict[int, Any] (whether that comes from normal type evaluation or a cast) to an attribute whose type is declared as dict[int, int] | None, the assignment is allowed because dict[int, Any] is assignable to dict[int, int] | None. Type narrowing is applied on assignment. The type dict[int, int] | None is narrowed to dict[int, int] in this case. The reveal_type call displays the locally-narrowed type at that location within the program.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by amacfie-tc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants