diff options
author | Patrick Reader <pxeger@protonmail.com> | 2020-09-16 04:58:32 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-09-16 04:58:32 (GMT) |
commit | 0705ec8a149e27023b0420ae0366d16255f6c9f7 (patch) | |
tree | cc477b4be6306f9b2007f4d2084440e7c965a643 /Lib | |
parent | 22415ad62555d79bd583b4a7d6a96006624a8277 (diff) | |
download | cpython-0705ec8a149e27023b0420ae0366d16255f6c9f7.zip cpython-0705ec8a149e27023b0420ae0366d16255f6c9f7.tar.gz cpython-0705ec8a149e27023b0420ae0366d16255f6c9f7.tar.bz2 |
bpo-41792: Add is_typeddict function to typing.py (GH-22254)
Closes issue41792.
Also closes https://github.com/python/typing/issues/751.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/test/test_typing.py | 7 | ||||
-rw-r--r-- | Lib/typing.py | 15 |
2 files changed, 22 insertions, 0 deletions
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 05140fc..42aa430 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -16,6 +16,7 @@ from typing import Generic, ClassVar, Final, final, Protocol from typing import cast, runtime_checkable from typing import get_type_hints from typing import get_origin, get_args +from typing import is_typeddict from typing import no_type_check, no_type_check_decorator from typing import Type from typing import NewType @@ -3900,6 +3901,12 @@ class TypedDictTests(BaseTestCase): 'voice': str, } + def test_is_typeddict(self): + assert is_typeddict(Point2D) is True + assert is_typeddict(Union[str, int]) is False + # classes, not instances + assert is_typeddict(Point2D()) is False + class IOTests(BaseTestCase): diff --git a/Lib/typing.py b/Lib/typing.py index 2aedbeb..8c61bd8 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -103,6 +103,7 @@ __all__ = [ 'get_args', 'get_origin', 'get_type_hints', + 'is_typeddict', 'NewType', 'no_type_check', 'no_type_check_decorator', @@ -1479,6 +1480,20 @@ def get_args(tp): return () +def is_typeddict(tp): + """Check if an annotation is a TypedDict class + + For example:: + class Film(TypedDict): + title: str + year: int + + is_typeddict(Film) # => True + is_typeddict(Union[list, str]) # => False + """ + return isinstance(tp, _TypedDictMeta) + + def no_type_check(arg): """Decorator to indicate that annotations are not type hints. |