-
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
Inferred type used instead of type hint with Optional for dict.get #5233
Comments
Pyright is correct here. The declared type of Mypy gets this wrong. Its behavior is inconsistent depending on whether the assignment takes place on the same line as a type declaration. If you move the assignment to the next line, mypy's behavior will change (and will now match pyright). data: dict[str, Any] = {}
number: Optional[int]
number = data.get("k")
reveal_type(number) # mypy: Any | None Refer to this documentation for more details. There is an open issue to fix this in mypy, but it hasn't been addressed yet. |
"narrowing" implies going from more abstract type (Any), to less abstract. And pyright in this case does otherwise. Consider following example: v: Any = data.get("k")
num: int = v # revealed type is `int`, it's narrowed, that's expected behaviour But: v: Optional[Any] = data.get("k")
num: Optional[int] = v # This is unexpected, revealed type is `Any | None` Also, old pyright |
What i want to point out, is: assigning |
There was a bug in a previous version of pyright that caused inconsistent behavior and possible loss of an
That's not an "expansion" of the type. The type As I said, there are plans for mypy to match this (correct) behavior. You can already observe this same behavior in mypy if you move the assignment to a second line. This isn't a bug. It's working as intended. |
Describe the bug
In this example type is inferred as Any, instead of using type hint.
To Reproduce
Expected behavior
Mypy does this correctly:
VS Code extension or command-line
pyright version: 1.1.311 and
main
The text was updated successfully, but these errors were encountered: