Skip to content

dict.update has incorrect variance for one of its overloads #3551

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

Open
lazytype opened this issue Dec 20, 2019 · 3 comments
Open

dict.update has incorrect variance for one of its overloads #3551

lazytype opened this issue Dec 20, 2019 · 3 comments
Labels
stubs: false positive Type checkers report false errors

Comments

@lazytype
Copy link
Contributor

from typing import Dict, Union

d: Dict[Union[str, int], None] = {}

e: Dict[str, None] = {}

# not ok
d.update(e)

# ok
d.update(e.items())

# ok
for key, value in e.items():
    d[key] = value
@ilevkivskyi
Copy link
Member

It looks like a possible solution here is to define a hidden typeshed-only supertype of Mapping (maybe call it _Mapping) that will be covariant in key type. We can then use it to annotate some built-in function and method arguments where we know it is safe.

@srittau srittau added the stubs: false positive Type checkers report false errors label Jan 5, 2020
@rohitkg98
Copy link
Contributor

Most Mutable containers are invariant. You can read more about that in details here: generics. For Dict(Mapping), it has been discussed in detail here. That said, you may try out the Protocol: SupportsItems, to have a covariant mapping of a dictionary.

@JelleZijlstra
Copy link
Member

Just to clarify, mypy produces this error on the original sample:

main.py:8: error: Argument 1 to "update" of "dict" has incompatible type "Dict[str, None]"; expected "Mapping[Union[str, int], None]"

The problem (as Ivan said) is that dict-like types are invariant in their key type, but here we want it to be covariant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: false positive Type checkers report false errors
Projects
None yet
Development

No branches or pull requests

5 participants