[3.9] bpo-38908: Fix issue when non runtime_protocol does not raise TypeError (GH-26067) (GH-26075)

(cherry picked from commit c40486a)

Co-authored-by: Yurii Karabas 1998uriyyo@gmail.com

Automerge-Triggered-By: GH:gvanrossum
This commit is contained in:
Ken Jin 2021-05-13 01:04:43 +08:00 committed by GitHub
parent 1be9396061
commit 88136bbd05
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 4 deletions

View file

@ -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):

View file

@ -1079,14 +1079,14 @@ def _no_init(self, *args, **kwargs):
raise TypeError('Protocols cannot be instantiated')
def _allow_reckless_class_cheks():
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
@ -1106,6 +1106,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)):
@ -1168,12 +1176,12 @@ class Protocol(Generic, metaclass=_ProtocolMeta):
# First, perform various sanity checks.
if not getattr(cls, '_is_runtime_protocol', False):
if _allow_reckless_class_cheks():
if _allow_reckless_class_checks():
return NotImplemented
raise TypeError("Instance and class checks can only be used with"
" @runtime_checkable protocols")
if not _is_callable_members_only(cls):
if _allow_reckless_class_cheks():
if _allow_reckless_class_checks():
return NotImplemented
raise TypeError("Protocols with non-method members"
" don't support issubclass()")

View file

@ -0,0 +1,5 @@
Fix issue where :mod:`typing` protocols without the ``@runtime_checkable``
decorator did not raise a ``TypeError`` when used with ``issubclass`` and
``isinstance``. Now, subclassses of ``typing.Protocol`` will raise a
``TypeError`` when used with with those checks.
Patch provided by Yurii Karabas.