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

dict.__init__() and dict.update() don't match #6056

Open
Akuli opened this issue Sep 20, 2021 · 1 comment
Open

dict.__init__() and dict.update() don't match #6056

Akuli opened this issue Sep 20, 2021 · 1 comment

Comments

@Akuli
Copy link
Collaborator

Akuli commented Sep 20, 2021

@overload
def __init__(self: dict[_KT, _VT]) -> None: ...
@overload
def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ...
@overload
def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ...
@overload
def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
# Next overload is for dict(string.split(sep) for string in iterable)
# Cannot be Iterable[Sequence[_T]] or otherwise dict(["foo", "bar", "baz"]) is not an error
@overload
def __init__(self: dict[str, str], iterable: Iterable[list[str]]) -> None: ...

@overload
def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
@overload
def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
@overload
def update(self, **kwargs: _VT) -> None: ...

In stubs, __init__ has 5 overloads and update() has 3 overloads. But at runtime, dict.update() accepts everything that dict.__init__ accepts. For example:

>>> d={}
>>> d.update((s.split('=') for s in ['a=b', 'c=d']), lol='wut')
>>> d
{'a': 'b', 'c': 'd', 'lol': 'wut'}
@JelleZijlstra
Copy link
Member

Concrete changes that could be made are:

  • Make the mapping variant of .update take SupportsKeysAndGetItem instead of Mapping (Widen MutableMapping.update type #6653)
  • Allow **kwargs to update() only if the key type is str. I haven't tried this yet and it may run into tricky variance issues. (What if the key type is a Literal over particular strings?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants