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

Improve several stdlib setdefault methods #9612

Merged
merged 2 commits into from
Jan 31, 2023

Conversation

AlexWaygood
Copy link
Member

@AlexWaygood AlexWaygood commented Jan 29, 2023

  1. Improve the first overload of MutableMapping.setdefault. It's okay to specify a value for the default parameter and still have this overload match, as long as the value passed for this parameter is None. Adjust collections.OrderedDict.setdefault and weakref.WeakKeyDictionary.setdefault to match. Add @JelleZijlstra's test cases from Improve type for setdefault() #6941 (comment), to make sure that the method is still working as expected.
  2. Bring ChainMap.setdefault in sync with MutableMapping.setdefault. At runtime, it is directly inherited from MutableMapping.setdefault. (We don't do that in the stub because we pretend MutableMapping.setdefault has positional-only parameters so that dict can inherit from MutableMapping without having to type: ignore the setdefault method.)
  3. Remove the = ... from weakref.WeakValueDictionary.setdefault. This has got a default value of None at runtime, but it will always error out if you don't specify a value for the default parameter. (This is because you can't create a weak reference to None.) It will serve users better if we specify in the stub that you have to provide a value for the default parameter.

Refs #9608.

@AlexWaygood
Copy link
Member Author

This is not a comprehensive review of all setdefault methods across the stdlib, but I haven't got the energy for that right now.

@github-actions
Copy link
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

urllib3 (https://github.com/urllib3/urllib3)
+ src/urllib3/_collections.py:270: error: Signature of "setdefault" incompatible with supertype "MutableMapping"  [override]
+ src/urllib3/_collections.py:270: note:      Superclass:
+ src/urllib3/_collections.py:270: note:          @overload
+ src/urllib3/_collections.py:270: note:          def setdefault(self, str, None = ..., /) -> Optional[str]
+ src/urllib3/_collections.py:270: note:          @overload
+ src/urllib3/_collections.py:270: note:          def setdefault(self, str, str, /) -> str
+ src/urllib3/_collections.py:270: note:      Subclass:
+ src/urllib3/_collections.py:270: note:          def setdefault(self, key: str, default: str = ...) -> str

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 this pull request may close these issues.

2 participants