Visitar URL original
gh-104935: typing: Fix interactions between @runtime_checkable and Generic by JelleZijlstra · Pull Request #104939 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Better approach
  • Loading branch information
JelleZijlstra committed May 25, 2023
commit f299fbdfd107afd378de3336c5235d6b33d92c1d
10 changes: 5 additions & 5 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2485,17 +2485,17 @@ def test_runtime_checkable_generic(self):
@runtime_checkable
class Foo[T](Protocol):
def meth(self) -> T: ...

class Impl:
def meth(self) -> int: ...

self.assertIsSubclass(Impl, Foo)

class NotImpl:
def method(self) -> int: ...

self.assertNotIsSubclass(NotImpl, Foo)

def test_pep695_generics_can_be_runtime_checkable(self):
@runtime_checkable
class HasX(Protocol):
Expand Down
6 changes: 3 additions & 3 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1894,7 +1894,7 @@ def _proto_hook(other):
annotations = getattr(base, '__annotations__', {})
if (isinstance(annotations, collections.abc.Mapping) and
attr in annotations and
issubclass(other, Generic) and other._is_protocol):
issubclass(other, Generic) and getattr(other, '_is_protocol', False)):
break
else:
return NotImplemented
Expand All @@ -1912,7 +1912,7 @@ def _proto_hook(other):
if not (base in (object, Generic) or
base.__module__ in _PROTO_ALLOWLIST and
base.__name__ in _PROTO_ALLOWLIST[base.__module__] or
issubclass(base, Generic) and base._is_protocol):
issubclass(base, Generic) and getattr(base, '_is_protocol', False)):
raise TypeError('Protocols can only inherit from other'
' protocols, got %r' % base)
if cls.__init__ is Protocol.__init__:
Expand Down Expand Up @@ -2059,7 +2059,7 @@ def close(self): ...
Warning: this will check only the presence of the required methods,
not their type signatures!
"""
if not issubclass(cls, Generic) or not cls._is_protocol:
if not issubclass(cls, Generic) or not getattr(cls, '_is_protocol', False):
raise TypeError('@runtime_checkable can be only applied to protocol classes,'
' got %r' % cls)
cls._is_runtime_protocol = True
Expand Down
5 changes: 0 additions & 5 deletions Objects/typevarobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1640,11 +1640,6 @@ int _Py_initialize_generic(PyInterpreterState *interp)
MAKE_TYPE(paramspecargs);
MAKE_TYPE(paramspeckwargs);
#undef MAKE_TYPE
if (PyDict_SetItemString(interp->cached_objects.generic_type->tp_dict,
"_is_protocol", Py_False) < 0) {
return -1;
}
PyType_Modified(interp->cached_objects.generic_type);
return 0;
}

Expand Down