Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[3.11] gh-74690: Add more tests for runtime-checkable protocols (GH-103347) #103350

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

Merged
merged 1 commit into from
Apr 7, 2023
Merged
Changes from all 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
41 changes: 39 additions & 2 deletions 41 Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2572,6 +2572,22 @@ def meth(x): ...
class PG(Protocol[T]):
def meth(x): ...

@runtime_checkable
class WeirdProto(Protocol):
meth = str.maketrans

@runtime_checkable
class WeirdProto2(Protocol):
meth = lambda *args, **kwargs: None

class CustomCallable:
def __call__(self, *args, **kwargs):
pass

@runtime_checkable
class WeirderProto(Protocol):
meth = CustomCallable()

class BadP(Protocol):
def meth(x): ...

Expand All @@ -2581,8 +2597,15 @@ def meth(x): ...
class C:
def meth(x): ...

self.assertIsInstance(C(), P)
self.assertIsInstance(C(), PG)
class C2:
def __init__(self):
self.meth = lambda: None

for klass in C, C2:
for proto in P, PG, WeirdProto, WeirdProto2, WeirderProto:
with self.subTest(klass=klass.__name__, proto=proto.__name__):
self.assertIsInstance(klass(), proto)

with self.assertRaises(TypeError):
isinstance(C(), PG[T])
with self.assertRaises(TypeError):
Expand Down Expand Up @@ -2735,6 +2758,20 @@ def __init__(self, x):
self.assertIsInstance(C(1), P)
self.assertIsInstance(C(1), PG)

def test_protocols_isinstance_monkeypatching(self):
@runtime_checkable
class HasX(Protocol):
x: int

class Foo: ...

f = Foo()
self.assertNotIsInstance(f, HasX)
f.x = 42
self.assertIsInstance(f, HasX)
del f.x
self.assertNotIsInstance(f, HasX)

def test_protocol_checks_after_subscript(self):
class P(Protocol[T]): pass
class C(P[T]): pass
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.