-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Persist type checks across later conditional blocks with the same condition #2199
Comments
This would involve tracking types of variables that depend on types of other variables. For example, it would need to remember that These would both add significant complexity and performance/memory overhead to the type evaluator. I don't know of any type checker in any language that does this. I'll think about this a bit more, but it's likely that this problem is unsolvable except in the simplest of cases, and even then it might add so much overhead and complexity as to be undesirable. |
I can't think of a way to do this without adding significant complexity and a massive performance penalty. Like I said above, I'm not aware of any static type checker or compiler in any language that does this, and there's good reason for it. |
Part of the desired behavior seems to be supported by from __future__ import annotations
def func(flag: bool, value: str | None) -> None:
if flag:
num = 1
assert value
reveal_type(num)
reveal_type(value)
if flag:
reveal_type(num)
reveal_type(value) Here are the types given by
|
That just looks like a consequence of the fact that mypy doesn't track whether local variables have been bound. It sees a single assignment to |
Mypy doesn't do any tracking of unbound values. It has been an open feature request for a long time. |
Thanks. Sorry for the noise. |
Describe the feature
It would be nice for later use of the same conditional check to share its type "context", so that the likes of bound variables and type narrowing can be referenced later, without needing to set otherwise-unused defaults or recheck types.
Current behaviour
Expected behavior
Because the same* condition is used, any type logic that applied within the previous uses of the condition should apply here too. In this case,
num
is always defined andvalue
is always narrowed whenflag
is set.*In my case I am looking at a single
bool
flag here for the condition, so I'd be happy with an exact syntax match rather than an equivalence if the latter is trickier to achieve.VS Code extension or command-line
Pyright 1.1.162 in VSCode.
The text was updated successfully, but these errors were encountered: