File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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.
Original file line number Diff line number Diff line change 1616from typing import cast , runtime_checkable
1717from typing import get_type_hints
1818from typing import get_origin , get_args
19+ from typing import is_typeddict
1920from typing import no_type_check , no_type_check_decorator
2021from typing import Type
2122from 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
39043911class IOTests (BaseTestCase ):
39053912
Original file line number Diff line number Diff line change 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+
14821497def no_type_check (arg ):
14831498 """Decorator to indicate that annotations are not type hints.
14841499
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