10000 bpo-38008: Move builtin protocol whitelist to mapping instead of list… · python/cpython@52baf90 · GitHub
[go: up one dir, main page]

Skip to content

Commit 52baf90

Browse files
bpo-38008: Move builtin protocol whitelist to mapping instead of list (GH-15647)
Fixes https://bugs.python.org/issue38008 (cherry picked from commit 692a0dc) Co-authored-by: Divij Rajkumar <drajkuma1@gmail.com>
1 parent 1e17c4d commit 52baf90

File tree

3 files changed

+20
-5
lines changed

3 files changed

+20
-5
lines changed

Lib/test/test_typing.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1381,6 +1381,14 @@ def close(self):
13811381
self.assertIsSubclass(B, Custom)
13821382
self.assertNotIsSubclass(A, Custom)
13831383

1384+
def test_builtin_protocol_whitelist(self):
1385+
with self.assertRaises(TypeError):
1386+
class CustomProtocol(TestCase, Protocol):
1387+
pass
1388+
1389+
class CustomContextManager(typing.ContextManager, Protocol):
1390+
pass
1391+
13841392
class GenericTests(BaseTestCase):
13851393

13861394
def test_basics(self):

Lib/typing.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -989,10 +989,13 @@ def _allow_reckless_class_cheks():
989989
return True
990990

991991

992-
_PROTO_WHITELIST = ['Callable', 'Awaitable',
993-
'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
994-
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
995-
'ContextManager', 'AsyncContextManager']
992+
_PROTO_WHITELIST = {
993+
'collections.abc': [
994+
'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
995+
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
996+
],
997+
'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
998+
}
996999

9971000

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

0 commit comments

Comments
 (0)
0