diff options
author | Yurii Karabas <1998uriyyo@gmail.com> | 2021-05-12 15:47:49 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-05-12 15:47:49 (GMT) |
commit | c40486a32d7e37b01ead94e701d69847f5b60e30 (patch) | |
tree | ca42f8aad68e8e6bfb324017b8a79f8207de4c5d /Lib | |
parent | 9b06e4b535a3a0af495604778d4010a4677478cc (diff) | |
download | cpython-c40486a32d7e37b01ead94e701d69847f5b60e30.zip cpython-c40486a32d7e37b01ead94e701d69847f5b60e30.tar.gz cpython-c40486a32d7e37b01ead94e701d69847f5b60e30.tar.bz2 |
bpo-38908: Fix issue when non runtime_protocol failed to raise TypeError (#26067)
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/test/test_typing.py | 8 | ||||
-rw-r--r-- | Lib/typing.py | 12 |
2 files changed, 18 insertions, 2 deletions
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 47dc0b9..a2a5d8f 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -1422,6 +1422,14 @@ class ProtocolTests(BaseTestCase): class CustomContextManager(typing.ContextManager, Protocol): pass + def test_non_runtime_protocol_isinstance_check(self): + class P(Protocol): + x: int + + with self.assertRaisesRegex(TypeError, "@runtime_checkable"): + isinstance(1, P) + + class GenericTests(BaseTestCase): def test_basics(self): diff --git a/Lib/typing.py b/Lib/typing.py index a51452b..ca47a6f 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -1343,14 +1343,14 @@ def _no_init(self, *args, **kwargs): raise TypeError('Protocols cannot be instantiated') -def _allow_reckless_class_checks(): +def _allow_reckless_class_checks(depth=3): """Allow instance and class checks for special stdlib modules. The abc and functools modules indiscriminately call isinstance() and issubclass() on the whole MRO of a user class, which may contain protocols. """ try: - return sys._getframe(3).f_globals['__name__'] in ['abc', 'functools'] + return sys._getframe(depth).f_globals['__name__'] in ['abc', 'functools'] except (AttributeError, ValueError): # For platforms without _getframe(). return True @@ -1370,6 +1370,14 @@ class _ProtocolMeta(ABCMeta): def __instancecheck__(cls, instance): # We need this method for situations where attributes are # assigned in __init__. + if ( + getattr(cls, '_is_protocol', False) and + not getattr(cls, '_is_runtime_protocol', False) and + not _allow_reckless_class_checks(depth=2) + ): + raise TypeError("Instance and class checks can only be used with" + " @runtime_checkable protocols") + if ((not getattr(cls, '_is_protocol', False) or _is_callable_members_only(cls)) and issubclass(instance.__class__, cls)): |