Skip to content

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

Open

Description

@Akuli

@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'}

Activity

  1. added a commit that references this issue on Dec 22, 2021
  2. JelleZijlstra commented on Dec 22, 2021

    @JelleZijlstra
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions