Skip to content

Commit 0705ec8

Browse files
authored
bpo-41792: Add is_typeddict function to typing.py (pythonGH-22254)
Closes issue41792. Also closes python/typing#751.
1 parent 22415ad commit 0705ec8

File tree

4 files changed

+42
-0
lines changed

4 files changed

+42
-0
lines changed

Doc/library/typing.rst

+14
Original file line numberDiff line numberDiff line change
@@ -1658,6 +1658,20 @@ Introspection helpers
16581658

16591659
.. versionadded:: 3.8
16601660

1661+
.. function:: is_typeddict(tp)
1662+
1663+
Check if an annotation is a TypedDict class.
1664+
1665+
For example::
1666+
class Film(TypedDict):
1667+
title: str
1668+
year: int
1669+
1670+
is_typeddict(Film) # => True
1671+
is_typeddict(Union[list, str]) # => False
1672+
1673+
.. versionadded:: 3.10
1674+
16611675
.. class:: ForwardRef
16621676

16631677
A class used for internal typing representation of string forward references.

Lib/test/test_typing.py

+7
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from typing import cast, runtime_checkable
1717
from typing import get_type_hints
1818
from typing import get_origin, get_args
19+
from typing import is_typeddict
1920
from typing import no_type_check, no_type_check_decorator
2021
from typing import Type
2122
from typing import NewType
@@ -3900,6 +3901,12 @@ class Cat(Animal):
39003901
'voice': str,
39013902
}
39023903

3904+
def test_is_typeddict(self):
3905+
assert is_typeddict(Point2D) is True
3906+
assert is_typeddict(Union[str, int]) is False
3907+
# classes, not instances
3908+
assert is_typeddict(Point2D()) is False
3909+
39033910

39043911
class IOTests(BaseTestCase):
39053912

Lib/typing.py

+15
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@
103103
'get_args',
104104
'get_origin',
105105
'get_type_hints',
106+
'is_typeddict',
106107
'NewType',
107108
'no_type_check',
108109
'no_type_check_decorator',
@@ -1479,6 +1480,20 @@ def get_args(tp):
14791480
return ()
14801481

14811482

1483+
def is_typeddict(tp):
1484+
"""Check if an annotation is a TypedDict class
1485+
1486+
For example::
1487+
class Film(TypedDict):
1488+
title: str
1489+
year: int
1490+
1491+
is_typeddict(Film) # => True
1492+
is_typeddict(Union[list, str]) # => False
1493+
"""
1494+
return isinstance(tp, _TypedDictMeta)
1495+
1496+
14821497
def no_type_check(arg):
14831498
"""Decorator to indicate that annotations are not type hints.
14841499
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Add is_typeddict function to typing.py to check if a type is a TypedDict
2+
class
3+
4+
Previously there was no way to check that without using private API. See the
5+
`relevant issue in python/typing
6+
<https://github.com/python/typing/issues/751>`

0 commit comments

Comments
 (0)