Skip to content

Add a partial, covariant Mapping type #47

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

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/test_typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2985,11 +2985,13 @@ def test_all_names_in___all__(self):
exclude = {
'GenericMeta',
'KT',
'KT_co',
'PEP_560',
'T',
'T_co',
'T_contra',
'VT',
'VT_co',
}
actual_names = {
name for name in dir(typing_extensions)
Expand Down
24 changes: 24 additions & 0 deletions src/typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
'TypedDict',

# Structural checks, a.k.a. protocols.
'MappingAuxiliary',
'SupportsIndex',

# One-off things.
Expand Down Expand Up @@ -145,7 +146,9 @@ def _collect_type_vars(types, typevar_types=None):
# (These are not for export.)
T = typing.TypeVar('T') # Any type.
KT = typing.TypeVar('KT') # Key type.
KT_co = typing.TypeVar('KT', covariant=True) # Covariant key type.
VT = typing.TypeVar('VT') # Value type.
VT_co = typing.TypeVar('VT', covariant=True) # Value type.
T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.

Expand Down Expand Up @@ -603,6 +606,27 @@ def runtime_checkable(cls):
runtime = runtime_checkable


# Not yet ported to typing, but who knows
if hasattr(typing, 'MappingAuxiliary'):
MappingAuxiliary = typing.MappingAuxiliary
else:
@runtime_checkable
class MappingAuxiliary(typing.Collection[KT_co], Protocol[KT_co, VT_co]):
"""Represents the covariant sub-protocol of the Mapping type.

This is useful for annotating function parameters where you really want a
Mapping, but only interact with it covariantly with regards to keys.
"""
def items(self) -> typing.ItemsView[KT_co, VT_co]:
...

def keys(self) -> typing.KeysView[KT_co]:
...

def values(self) -> typing.ValuesView[VT_co]:
...


# 3.8+
if hasattr(typing, 'SupportsIndex'):
SupportsIndex = typing.SupportsIndex
Expand Down