File tree 4 files changed +42
-0
lines changed
4 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -1658,6 +1658,20 @@ Introspection helpers
1658
1658
1659
1659
.. versionadded :: 3.8
1660
1660
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
+
1661
1675
.. class :: ForwardRef
1662
1676
1663
1677
A class used for internal typing representation of string forward references.
Original file line number Diff line number Diff line change 16
16
from typing import cast , runtime_checkable
17
17
from typing import get_type_hints
18
18
from typing import get_origin , get_args
19
+ from typing import is_typeddict
19
20
from typing import no_type_check , no_type_check_decorator
20
21
from typing import Type
21
22
from typing import NewType
@@ -3900,6 +3901,12 @@ class Cat(Animal):
3900
3901
'voice' : str ,
3901
3902
}
3902
3903
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
+
3903
3910
3904
3911
class IOTests (BaseTestCase ):
3905
3912
Original file line number Diff line number Diff line change 103
103
'get_args' ,
104
104
'get_origin' ,
105
105
'get_type_hints' ,
106
+ 'is_typeddict' ,
106
107
'NewType' ,
107
108
'no_type_check' ,
108
109
'no_type_check_decorator' ,
@@ -1479,6 +1480,20 @@ def get_args(tp):
1479
1480
return ()
1480
1481
1481
1482
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
+
1482
1497
def no_type_check (arg ):
1483
1498
"""Decorator to indicate that annotations are not type hints.
1484
1499
Original file line number Diff line number Diff line change
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> `
You can’t perform that action at this time.
0 commit comments