-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Add protocols SequenceLike and MappingLike
#15152
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
base: main
Are you sure you want to change the base?
Conversation
`Sequence` and `Mapping` are commonly used in argument types. This can be problematic, since they are not protocols, making it impossible to safely duck type or mock them. Also, not all sequence- or mapping-like types derive from these ABCs at runtime, although in typeshed we often pretend they do. Ideally we'd be able to avoid this discrepancy in the far future. Finally, the ABCs sometimes make more API promises than their sub-classes fulfill. For example, `Mapping` arguments are keyword-or-positional, while its most important subtype `dict` only accepts positional arguments. These protocols have tighter guarantees. `SequenceLike` contains most, `MappingLike` all methods from their respective types, making them an easy substitute in argument types.
This comment has been minimized.
This comment has been minimized.
|
Why should we use these rather than more precise protocols like |
|
For convenience. I still think using the more precise protocols is the better option in 90% of cases, but sometimes this would be inconvenient, especially as long as we don't have easy protocol composition (via intersections). See also the large amount of |
|
Also, cf. PyCQA/flake8-pyi#525 |
jorenham
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yea this seems useful, and I like the NumPy-esque naming :)
Speaking of NumPy, I left a suggestion that would make np.ndarray assignable to SequenceLike.
This comment has been minimized.
This comment has been minimized.
|
According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉 |
SequenceandMappingare commonly used in argument types. This canbe problematic, since they are not protocols, making it impossible to
safely duck type or mock them. Also, not all sequence- or mapping-like
types derive from these ABCs at runtime, although in typeshed we often
pretend they do. Ideally we'd be able to avoid this discrepancy in the
far future. Finally, the ABCs sometimes make more API promises than
their sub-classes fulfill. For example,
Mappingarguments arekeyword-or-positional, while its most important subtype
dictonlyaccepts positional arguments. These protocols have tighter guarantees.
SequenceLikecontains most,MappingLikeall methods from theirrespective types, making them an easy substitute in argument types.