Skip to content

Conversation

@srittau
Copy link
Collaborator

@srittau srittau commented Jul 10, 2020

typing.Mapping is not a protocol, which has caused problems in the past.
(E.g. #3569, see also #3576.) This
introduces a few narrow protocols to _typeshed.pyi that can be used in
place of Mapping.

Not all uses of Mapping can be replaced. For example, cgi.FieldStorage
explictly checks whether the supplied headers argument is a Mapping
instance.

srittau added 2 commits July 10, 2020 10:15
typing.Mapping is not a protocol, which has caused problems in the past.
(E.g. python#3569, see also python#3576.) This
introduces a few narrow protocols to _typeshed.pyi that can be used in
place of Mapping.

Not all uses of Mapping can be replaced. For example, cgi.FieldStorage
explictly checks whether the supplied headers argument is a Mapping
instance.
def items(self) -> AbstractSet[Tuple[_KT_co, _VT_co]]: ...

class SupportsGetItem(Container[_KT_contra], Protocol[_KT_contra, _VT_co]):
def __getitem__(self, __k: _KT_contra) -> _VT_co: ...
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See python/typing#273 and #550 for some previous discussion on the variance of Mapping (not directly relevant here).

@JelleZijlstra JelleZijlstra merged commit 9ad8ed3 into python:master Jul 12, 2020
@srittau srittau deleted the mapping-protocol branch July 12, 2020 18:28
@Akuli
Copy link
Collaborator

Akuli commented Aug 2, 2020

For example, TopologicalSorter.__init__ takes a mapping and only uses the .items() method. What happens if it's changed to instead loop over the mapping to get the keys and call __getitem__ to get the values in a future version of Python? Then requiring SupportsItems instead of Mapping will be incorrect. The documentation says that the argument should be "a mapping", rather than saying "an object with .items()".

@srittau
Copy link
Collaborator Author

srittau commented Aug 2, 2020

If the implementation changes, the stubs need to change as well. We tend to follow implementation, not documentation in typeshed.

@torstenrudolf
Copy link

is there a way I can use the SupportsGetItem in type annotations in my code? I cannot figure out how to import it.

@hauntsaninja
Copy link
Collaborator

Look at the comment at the top of the file :-)

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.

5 participants