Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-104935: typing: Fix interactions between @runtime_checkable and Generic #104939

Merged
merged 5 commits into from
May 25, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
40 changes: 40 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2472,6 +2472,46 @@ def f():
self.assertNotIsSubclass(types.FunctionType, P)
self.assertNotIsInstance(f, P)

def test_runtime_checkable_generic_non_protocol(self):
# Make sure this doesn't raise AttributeError
with self.assertRaisesRegex(
TypeError,
"@runtime_checkable can be only applied to protocol classes",
):
@runtime_checkable
class Foo[T]: ...

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):
x: int
class Bar[T]:
x: T
def __init__(self, x):
self.x = x
class Capybara[T]:
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved
y: str
def __init__(self, y):
self.y = y

self.assertIsInstance(Bar(1), HasX)
self.assertNotIsInstance(Capybara('a'), HasX)

def test_everything_implements_empty_protocol(self):
@runtime_checkable
class Empty(Protocol):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix bugs with the interaction between :func:`typing.runtime_checkable` and
:class:`typing.Generic` that were introduced by the :pep:`695`
implementation. All generic classes now again have an ``_is_protocol``
attribute. Patch by Jelle Zijlstra.
5 changes: 5 additions & 0 deletions Objects/typevarobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1640,6 +1640,11 @@ 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);
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved
return 0;
}

Expand Down