Replies: 1 comment
-
In general, locally-narrowed types cannot be used for variables captured by an inner scope. Pyright is able to use the locally-narrowed type under very specific circumstances where it can prove that the value of that variable does not change after the inner-scope definition (a In your toy sample above, you're violating the requirements that make it safe to use the locally-narrowed type, so pyright cannot use it in that case. It would normally fall back on the declared type of the variable in this case, but you haven't declared the type of I think this is a case where you're going to need to modify your code if you want it to work better with static type checking. Perhaps add some type declarations or change the names of some variables to avoid reusing the same variable name for different uses within the same scope. |
Beta Was this translation helpful? Give feedback.
-
I inherited some code that repeatedly uses different class wrappers, but in the end it is the same type no matter which branch was taken, it looks for example like this:
The inferred type for
A
and the return type islist[() -> Var | Foo | Baz | Unified]
.This comes a bit as a surprise as
a
does not change and is alwaysUnified
afterwards.Of course the value of
a
could change after the definition ofA
and the lambdas would return the new value.Nevertheless, I think the type of
A
could be improved to be:reveal_type(A) # list[() -> Unified | <aTypesAfterDefinitionOfA>*]
instead of being:
reveal_type(A) # list[() -> <aTypesBeforeDefinitionOfA>* | Unified | <aTypesAfterDefinitionOfA>*]
As long as
a
is not global/nonlocal.I assume this needs some backward/forward checking but in the end would avoid false types being inferred.
I wonder if such a change is feasible and could be an enhancement request or if something could go very wrong.
Below I included a toy example:
Code sample in pyright playground
Beta Was this translation helpful? Give feedback.
All reactions