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

Set and Dict generalizing the type unnecessarily #17238

Open
MalteEbner opened this issue May 13, 2024 · 0 comments
Open

Set and Dict generalizing the type unnecessarily #17238

MalteEbner opened this issue May 13, 2024 · 0 comments
Labels
bug mypy got something wrong

Comments

@MalteEbner
Copy link

MalteEbner commented May 13, 2024

Bug Report

See these two example functions:

def f(items: list[str] | list[int]) -> None:
    items_as_set: set[str] | set[int] = set(items)

def g(key_to_count: dict[str, float] | dict[int, float]) -> None:
    key_to_count_2: dict[str, float] | dict[int, float] = {k: v for k, v in key_to_count.items()}

Mypy 1.10.0 complains about the assignment in each of them:

test_mypy_dict.py:2: error: Incompatible types in assignment (expression has type "set[object]", variable has type "set[str] | set[int]")  [assignment]
test_mypy_dict.py:5: error: Incompatible types in assignment (expression has type "dict[str | int, float]", variable has type "dict[str, float] | dict[int, float]")  [assignment]

To Reproduce

Playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=83bde5f3f11470e94b6a680158649641

Expected Behavior

The set() or dict() operation applied on a variable that is either a list[str] | list[int] is always either a set[str] or set[int]. The same applies to function g using a dict. Thus the functions should not raise a mypy error.

Workarounds

I tried two workarounds:

  • Using a mixed type of list[str | int]. However, I get the type list[str] | list[int] by an external function, thus this is not compatible.
  • Using a generic. This is not working either.

See the playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=264490179628a0a214a2e5bd947b8ccf
image

@MalteEbner MalteEbner added the bug mypy got something wrong label May 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

1 participant