diff options
author | Jelle Zijlstra <jelle.zijlstra@gmail.com> | 2023-05-25 16:43:40 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-05-25 16:43:40 (GMT) |
commit | 2b7027d0b2ee2e102a24a0da27d01b8221f9351c (patch) | |
tree | 89fcf158a87d80b7799ee8daf51883bcdad23db0 /Lib/test/test_typing.py | |
parent | 77d7ec5aa978db05cfb6f83e7624ca195065ce11 (diff) | |
download | cpython-2b7027d0b2ee2e102a24a0da27d01b8221f9351c.zip cpython-2b7027d0b2ee2e102a24a0da27d01b8221f9351c.tar.gz cpython-2b7027d0b2ee2e102a24a0da27d01b8221f9351c.tar.bz2 |
gh-104935: typing: Fix interactions between `@runtime_checkable` and `Generic` (#104939)
---------
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Diffstat (limited to 'Lib/test/test_typing.py')
-rw-r--r-- | Lib/test/test_typing.py | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 46c8e74..d328b0e 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -2472,6 +2472,48 @@ class ProtocolTests(BaseTestCase): 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]: + 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): |