mirror of
https://github.com/python/cpython.git
synced 2025-10-17 20:28:43 +00:00
bpo-43766: Implement PEP 647 (User-Defined Type Guards) in typing.py (#25282)
This commit is contained in:
parent
d92513390a
commit
05ab4b60ab
5 changed files with 175 additions and 0 deletions
|
@ -26,6 +26,7 @@ from typing import Pattern, Match
|
|||
from typing import Annotated, ForwardRef
|
||||
from typing import TypeAlias
|
||||
from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs
|
||||
from typing import TypeGuard
|
||||
import abc
|
||||
import typing
|
||||
import weakref
|
||||
|
@ -4377,6 +4378,45 @@ class ConcatenateTests(BaseTestCase):
|
|||
self.assertEqual(C4.__parameters__, (T, P))
|
||||
|
||||
|
||||
class TypeGuardTests(BaseTestCase):
|
||||
def test_basics(self):
|
||||
TypeGuard[int] # OK
|
||||
|
||||
def foo(arg) -> TypeGuard[int]: ...
|
||||
self.assertEqual(gth(foo), {'return': TypeGuard[int]})
|
||||
|
||||
def test_repr(self):
|
||||
self.assertEqual(repr(TypeGuard), 'typing.TypeGuard')
|
||||
cv = TypeGuard[int]
|
||||
self.assertEqual(repr(cv), 'typing.TypeGuard[int]')
|
||||
cv = TypeGuard[Employee]
|
||||
self.assertEqual(repr(cv), 'typing.TypeGuard[%s.Employee]' % __name__)
|
||||
cv = TypeGuard[tuple[int]]
|
||||
self.assertEqual(repr(cv), 'typing.TypeGuard[tuple[int]]')
|
||||
|
||||
def test_cannot_subclass(self):
|
||||
with self.assertRaises(TypeError):
|
||||
class C(type(TypeGuard)):
|
||||
pass
|
||||
with self.assertRaises(TypeError):
|
||||
class C(type(TypeGuard[int])):
|
||||
pass
|
||||
|
||||
def test_cannot_init(self):
|
||||
with self.assertRaises(TypeError):
|
||||
TypeGuard()
|
||||
with self.assertRaises(TypeError):
|
||||
type(TypeGuard)()
|
||||
with self.assertRaises(TypeError):
|
||||
type(TypeGuard[Optional[int]])()
|
||||
|
||||
def test_no_isinstance(self):
|
||||
with self.assertRaises(TypeError):
|
||||
isinstance(1, TypeGuard[int])
|
||||
with self.assertRaises(TypeError):
|
||||
issubclass(int, TypeGuard)
|
||||
|
||||
|
||||
class AllTests(BaseTestCase):
|
||||
"""Tests for __all__."""
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue