Skip to content
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

False positive with variable key in Mapping with Optional value #10163

Open
aphedges opened this issue Mar 4, 2021 · 2 comments
Open

False positive with variable key in Mapping with Optional value #10163

aphedges opened this issue Mar 4, 2021 · 2 comments
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code

Comments

@aphedges
Copy link

aphedges commented Mar 4, 2021

Bug Report

When using a mapping with an Optional value type, accessing a value using a variable key instead of a literal key prevents a None check from working properly.

To Reproduce

  1. Put the following code in test.py:
from typing import Mapping, Optional

FOO: str = "foo"

def func(text: str) -> None:
    _ = text

data: Mapping[str, Optional[str]] = {FOO: "bar"}

if data[FOO] is not None:
    func(data[FOO])  # Line 11

if data["foo"] is not None:
    func(data["foo"])
  1. Run mypy test.py

Expected Behavior

mypy should not output any errors. As the above example shows, using a string literal instead of a variable containing a string does not cause any errors, even though the code is otherwise identical. The "Optional types and the None type" section of the documents says "supported checks for guarding against a None value include if x is not None", so this code should work.

Actual Behavior

mypy outputs the following:

test.py:11: error: Argument 1 to "func" has incompatible type "Optional[str]"; expected "str"  [arg-type]

Your Environment

  • Mypy version used: 0.812
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): show_error_codes = True
  • Python version used: 3.7.9
  • Operating system and version: macOS 10.15.7 (19H524)
@aphedges aphedges added the bug mypy got something wrong label Mar 4, 2021
@JukkaL
Copy link
Collaborator

JukkaL commented Mar 5, 2021

Yeah, mypy should probably be able to figure this out, at least if FOO is final:

FOO: Final = "foo"

This already works if you use a literal string as the key (e.g. data["foo"]).

@JukkaL JukkaL added the false-positive mypy gave an error on correct code label Mar 5, 2021
@aphedges
Copy link
Author

aphedges commented Mar 5, 2021

Using Final (from typing_extensions) for both FOO and data was one of the first things I tried, but I didn't include it in my example because it didn't change the error message at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code
Projects
None yet
Development

No branches or pull requests

2 participants