bpo-43766: Implement PEP 647 (User-Defined Type Guards) in typing.py (#25282)

This commit is contained in:
Ken Jin 2021-04-27 22:31:04 +08:00 committed by GitHub
parent d92513390a
commit 05ab4b60ab
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 175 additions and 0 deletions

View file

@ -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__."""