Skip to content

The type of __default= in dict.pop and dict.get doesn't look right #10293

Closed
@superbobry

Description

@superbobry

dict.pop is currently defined as

typeshed/stdlib/builtins.pyi

Lines 1086 to 1089 in 1851423

@overload
def pop(self, __key: _KT) -> _VT: ...
@overload
def pop(self, __key: _KT, __default: _VT | _T) -> _VT | _T: ...

Note the union with two type parameters as a type of __default=. This type is ambiguous if dict.pop is called with a value of type _VT. For example, given

d: dict[str, str]
d.pop("foo")

a type checker can choose any value for _T, since str is a subtype of str | _T regardless of what _T is.

It seems the union was introduced in 2fdcd2e, which unfortunately does not seem to give any reasoning for that. I think we should drop it and use _T instead in both dict.pop and dict.get (and similarly for MutableMapping), i.e.

class dict(Generic[_KT, _VT]):
   # ...
   @overload
   def pop(self, __key: _KT, __default: _T) -> _T: ...

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