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

[3.8] bpo-38008: Move builtin protocol whitelist to mapping instead of list (GH-15647) #16021

Merged
merged 1 commit into from
Sep 12, 2019
Merged
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
8 changes: 8 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1381,6 +1381,14 @@ def close(self):
self.assertIsSubclass(B, Custom)
self.assertNotIsSubclass(A, Custom)

def test_builtin_protocol_whitelist(self):
with self.assertRaises(TypeError):
class CustomProtocol(TestCase, Protocol):
pass

class CustomContextManager(typing.ContextManager, Protocol):
pass

class GenericTests(BaseTestCase):

def test_basics(self):
Expand Down
14 changes: 9 additions & 5 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -989,10 +989,13 @@ def _allow_reckless_class_cheks():
return True


_PROTO_WHITELIST = ['Callable', 'Awaitable',
'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
'ContextManager', 'AsyncContextManager']
_PROTO_WHITELIST = {
'collections.abc': [
'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
],
'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
}


class _ProtocolMeta(ABCMeta):
Expand Down Expand Up @@ -1105,7 +1108,8 @@ def _proto_hook(other):
# ... otherwise check consistency of bases, and prohibit instantiation.
for base in cls.__bases__:
if not (base in (object, Generic) or
base.__module__ == 'collections.abc' and base.__name__ in _PROTO_WHITELIST or
base.__module__ in _PROTO_WHITELIST and
base.__name__ in _PROTO_WHITELIST[base.__module__] or
issubclass(base, Generic) and base._is_protocol):
raise TypeError('Protocols can only inherit from other'
' protocols, got %r' % base)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix parent class check in protocols to correctly identify the module that
provides a builtin protocol, instead of assuming they all come from the
:mod:`collections.abc` module