Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 135c6a5

Browse files
authored
bpo-37049: PEP 589: Add TypedDict to typing module (GH-13573)
The implementation is straightforward and essentially is just copied from `typing_extensions`.
1 parent b891c46 commit 135c6a5

4 files changed

Lines changed: 222 additions & 1 deletion

File tree

Doc/library/typing.rst

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,39 @@ The module defines the following classes, functions and decorators:
878878
The ``_field_types`` and ``__annotations__`` attributes are
879879
now regular dictionaries instead of instances of ``OrderedDict``.
880880

881+
.. class:: TypedDict(dict)
882+
883+
A simple typed namespace. At runtime it is equivalent to
884+
a plain :class:`dict`.
885+
886+
``TypedDict`` creates a dictionary type that expects all of its
887+
instances to have a certain set of keys, where each key is
888+
associated with a value of a consistent type. This expectation
889+
is not checked at runtime but is only enforced by type checkers.
890+
Usage::
891+
892+
class Point2D(TypedDict):
893+
x: int
894+
y: int
895+
label: str
896+
897+
a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
898+
b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
899+
900+
assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
901+
902+
The type info for introspection can be accessed via ``Point2D.__annotations__``
903+
and ``Point2D.__total__``. To allow using this feature with older versions
904+
of Python that do not support :pep:`526`, ``TypedDict`` supports two additional
905+
equivalent syntactic forms::
906+
907+
Point2D = TypedDict('Point2D', x=int, y=int, label=str)
908+
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
909+
910+
See :pep:`589` for more examples and detailed rules of using ``TypedDict``
911+
with type checkers.
912+
913+
.. versionadded:: 3.8
881914

882915
.. function:: NewType(typ)
883916

Lib/test/test_typing.py

Lines changed: 104 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from typing import no_type_check, no_type_check_decorator
1919
from typing import Type
2020
from typing import NewType
21-
from typing import NamedTuple
21+
from typing import NamedTuple, TypedDict
2222
from typing import IO, TextIO, BinaryIO
2323
from typing import Pattern, Match
2424
import abc
@@ -1883,6 +1883,18 @@ def __str__(self):
18831883
def __add__(self, other):
18841884
return 0
18851885

1886+
Label = TypedDict('Label', [('label', str)])
1887+
1888+
class Point2D(TypedDict):
1889+
x: int
1890+
y: int
1891+
1892+
class LabelPoint2D(Point2D, Label): ...
1893+
1894+
class Options(TypedDict, total=False):
1895+
log_level: int
1896+
log_path: str
1897+
18861898
class HasForeignBaseClass(mod_generics_cache.A):
18871899
some_xrepr: 'XRepr'
18881900
other_a: 'mod_generics_cache.A'
@@ -2658,6 +2670,97 @@ def test_pickle(self):
26582670
self.assertEqual(jane2, jane)
26592671

26602672

2673+
class TypedDictTests(BaseTestCase):
2674+
def test_basics_functional_syntax(self):
2675+
Emp = TypedDict('Emp', {'name': str, 'id': int})
2676+
self.assertIsSubclass(Emp, dict)
2677+
self.assertIsSubclass(Emp, typing.MutableMapping)
2678+
self.assertNotIsSubclass(Emp, collections.abc.Sequence)
2679+
jim = Emp(name='Jim', id=1)
2680+
self.assertIs(type(jim), dict)
2681+
self.assertEqual(jim['name'], 'Jim')
2682+
self.assertEqual(jim['id'], 1)
2683+
self.assertEqual(Emp.__name__, 'Emp')
2684+
self.assertEqual(Emp.__module__, __name__)
2685+
self.assertEqual(Emp.__bases__, (dict,))
2686+
self.assertEqual(Emp.__annotations__, {'name': str, 'id': int})
2687+
self.assertEqual(Emp.__total__, True)
2688+
2689+
def test_basics_keywords_syntax(self):
2690+
Emp = TypedDict('Emp', name=str, id=int)
2691+
self.assertIsSubclass(Emp, dict)
2692+
self.assertIsSubclass(Emp, typing.MutableMapping)
2693+
self.assertNotIsSubclass(Emp, collections.abc.Sequence)
2694+
jim = Emp(name='Jim', id=1)
2695+
self.assertIs(type(jim), dict)
2696+
self.assertEqual(jim['name'], 'Jim')
2697+
self.assertEqual(jim['id'], 1)
2698+
self.assertEqual(Emp.__name__, 'Emp')
2699+
self.assertEqual(Emp.__module__, __name__)
2700+
self.assertEqual(Emp.__bases__, (dict,))
2701+
self.assertEqual(Emp.__annotations__, {'name': str, 'id': int})
2702+
self.assertEqual(Emp.__total__, True)
2703+
2704+
def test_typeddict_errors(self):
2705+
Emp = TypedDict('Emp', {'name': str, 'id': int})
2706+
self.assertEqual(TypedDict.__module__, 'typing')
2707+
jim = Emp(name='Jim', id=1)
2708+
with self.assertRaises(TypeError):
2709+
isinstance({}, Emp)
2710+
with self.assertRaises(TypeError):
2711+
isinstance(jim, Emp)
2712+
with self.assertRaises(TypeError):
2713+
issubclass(dict, Emp)
2714+
with self.assertRaises(TypeError):
2715+
TypedDict('Hi', x=1)
2716+
with self.assertRaises(TypeError):
2717+
TypedDict('Hi', [('x', int), ('y', 1)])
2718+
with self.assertRaises(TypeError):
2719+
TypedDict('Hi', [('x', int)], y=int)
2720+
2721+
def test_py36_class_syntax_usage(self):
2722+
self.assertEqual(LabelPoint2D.__name__, 'LabelPoint2D')
2723+
self.assertEqual(LabelPoint2D.__module__, __name__)
2724+
self.assertEqual(LabelPoint2D.__annotations__, {'x': int, 'y': int, 'label': str})
2725+
self.assertEqual(LabelPoint2D.__bases__, (dict,))
2726+
self.assertEqual(LabelPoint2D.__total__, True)
2727+
self.assertNotIsSubclass(LabelPoint2D, typing.Sequence)
2728+
not_origin = Point2D(x=0, y=1)
2729+
self.assertEqual(not_origin['x'], 0)
2730+
self.assertEqual(not_origin['y'], 1)
2731+
other = LabelPoint2D(x=0, y=1, label='hi')
2732+
self.assertEqual(other['label'], 'hi')
2733+
2734+
def test_pickle(self):
2735+
global EmpD # pickle wants to reference the class by name
2736+
EmpD = TypedDict('EmpD', name=str, id=int)
2737+
jane = EmpD({'name': 'jane', 'id': 37})
2738+
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2739+
z = pickle.dumps(jane, proto)
2740+
jane2 = pickle.loads(z)
2741+
self.assertEqual(jane2, jane)
2742+
self.assertEqual(jane2, {'name': 'jane', 'id': 37})
2743+
ZZ = pickle.dumps(EmpD, proto)
2744+
EmpDnew = pickle.loads(ZZ)
2745+
self.assertEqual(EmpDnew({'name': 'jane', 'id': 37}), jane)
2746+
2747+
def test_optional(self):
2748+
EmpD = TypedDict('EmpD', name=str, id=int)
2749+
2750+
self.assertEqual(typing.Optional[EmpD], typing.Union[None, EmpD])
2751+
self.assertNotEqual(typing.List[EmpD], typing.Tuple[EmpD])
2752+
2753+
def test_total(self):
2754+
D = TypedDict('D', {'x': int}, total=False)
2755+
self.assertEqual(D(), {})
2756+
self.assertEqual(D(x=1), {'x': 1})
2757+
self.assertEqual(D.__total__, False)
2758+
2759+
self.assertEqual(Options(), {})
2760+
self.assertEqual(Options(log_level=2), {'log_level': 2})
2761+
self.assertEqual(Options.__total__, False)
2762+
2763+
26612764
class IOTests(BaseTestCase):
26622765

26632766
def test_io(self):

Lib/typing.py

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@
8989
'Set',
9090
'FrozenSet',
9191
'NamedTuple', # Not really a type.
92+
'TypedDict', # Not really a type.
9293
'Generator',
9394

9495
# One-off things.
@@ -1490,6 +1491,89 @@ def __new__(self, typename, fields=None, **kwargs):
14901491
return _make_nmtuple(typename, fields)
14911492

14921493

1494+
def _dict_new(cls, *args, **kwargs):
1495+
return dict(*args, **kwargs)
1496+
1497+
1498+
def _typeddict_new(cls, _typename, _fields=None, **kwargs):
1499+
total = kwargs.pop('total', True)
1500+
if _fields is None:
1501+
_fields = kwargs
1502+
elif kwargs:
1503+
raise TypeError("TypedDict takes either a dict or keyword arguments,"
1504+
" but not both")
1505+
1506+
ns = {'__annotations__': dict(_fields), '__total__': total}
1507+
try:
1508+
# Setting correct module is necessary to make typed dict classes pickleable.
1509+
ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
1510+
except (AttributeError, ValueError):
1511+
pass
1512+
1513+
return _TypedDictMeta(_typename, (), ns)
1514+
1515+
1516+
def _check_fails(cls, other):
1517+
# Typed dicts are only for static structural subtyping.
1518+
raise TypeError('TypedDict does not support instance and class checks')
1519+
1520+
1521+
class _TypedDictMeta(type):
1522+
def __new__(cls, name, bases, ns, total=True):
1523+
"""Create new typed dict class object.
1524+
1525+
This method is called directly when TypedDict is subclassed,
1526+
or via _typeddict_new when TypedDict is instantiated. This way
1527+
TypedDict supports all three syntax forms described in its docstring.
1528+
Subclasses and instances of TypedDict return actual dictionaries
1529+
via _dict_new.
1530+
"""
1531+
ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
1532+
tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)
1533+
1534+
anns = ns.get('__annotations__', {})
1535+
msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
1536+
anns = {n: _type_check(tp, msg) for n, tp in anns.items()}
1537+
for base in bases:
1538+
anns.update(base.__dict__.get('__annotations__', {}))
1539+
tp_dict.__annotations__ = anns
1540+
if not hasattr(tp_dict, '__total__'):
1541+
tp_dict.__total__ = total
1542+
return tp_dict
1543+
1544+
__instancecheck__ = __subclasscheck__ = _check_fails
1545+
1546+
1547+
class TypedDict(dict, metaclass=_TypedDictMeta):
1548+
"""A simple typed namespace. At runtime it is equivalent to a plain dict.
1549+
1550+
TypedDict creates a dictionary type that expects all of its
1551+
instances to have a certain set of keys, where each key is
1552+
associated with a value of a consistent type. This expectation
1553+
is not checked at runtime but is only enforced by type checkers.
1554+
Usage::
1555+
1556+
class Point2D(TypedDict):
1557+
x: int
1558+
y: int
1559+
label: str
1560+
1561+
a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1562+
b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1563+
1564+
assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1565+
1566+
The type info can be accessed via Point2D.__annotations__. TypedDict
1567+
supports two additional equivalent forms::
1568+
1569+
Point2D = TypedDict('Point2D', x=int, y=int, label=str)
1570+
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1571+
1572+
The class syntax is only supported in Python 3.6+, while two other
1573+
syntax forms work for Python 2.7 and 3.2+
1574+
"""
1575+
1576+
14931577
def NewType(name, tp):
14941578
"""NewType creates simple unique types with almost zero
14951579
runtime overhead. NewType(name, tp) is considered a subtype of tp
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
PEP 589: Add ``TypedDict`` to the ``typing`` module.

0 commit comments

Comments
 (0)