summaryrefslogtreecommitdiffstats
path: root/Lib/typing.py
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2021-05-12 16:09:04 (GMT)
committerGitHub <noreply@github.com>2021-05-12 16:09:04 (GMT)
commita2d94a0a9b8ae95d7d2b7fc34b501da5242ec22c (patch)
treed69473e07ab467afb932ef0c7fd0fea8dbf7e0c2 /Lib/typing.py
parentbd5dfd6c8c133ccda4dddcba3a8c5a9ea1aa1d6b (diff)
downloadcpython-a2d94a0a9b8ae95d7d2b7fc34b501da5242ec22c.zip
cpython-a2d94a0a9b8ae95d7d2b7fc34b501da5242ec22c.tar.gz
cpython-a2d94a0a9b8ae95d7d2b7fc34b501da5242ec22c.tar.bz2
bpo-38908: Fix issue when non runtime_protocol failed to raise TypeError (GH-26067)
(cherry picked from commit c40486a32d7e37b01ead94e701d69847f5b60e30) Co-authored-by: Yurii Karabas <1998uriyyo@gmail.com>
Diffstat (limited to 'Lib/typing.py')
-rw-r--r--Lib/typing.py12
1 files changed, 10 insertions, 2 deletions
diff --git a/Lib/typing.py b/Lib/typing.py
index 301a477..26efe4a 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)):