File: supported-types.rst

package info (click to toggle)
python-msgspec 0.19.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,356 kB
  • sloc: javascript: 23,944; ansic: 20,540; python: 20,465; makefile: 29; sh: 19
file content (1620 lines) | stat: -rw-r--r-- 51,284 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
Supported Types
===============

``msgspec`` uses Python `type annotations`_ to describe the expected types.
Most combinations of the following types are supported (with a few restrictions):

**Builtin Types**

- `None`
- `bool`
- `int`
- `float`
- `str`
- `bytes`
- `bytearray`
- `tuple` / `typing.Tuple`
- `list` / `typing.List`
- `dict` / `typing.Dict`
- `set` / `typing.Set`
- `frozenset` / `typing.FrozenSet`

**Msgspec types**

- `msgspec.msgpack.Ext`
- `msgspec.Raw`
- `msgspec.UNSET`
- `msgspec.Struct` types

**Standard Library Types**

- `datetime.datetime`
- `datetime.date`
- `datetime.time`
- `datetime.timedelta`
- `uuid.UUID`
- `decimal.Decimal`
- `enum.Enum` types
- `enum.IntEnum` types
- `enum.StrEnum` types
- `enum.Flag` types
- `enum.IntFlag` types
- `dataclasses.dataclass` types

**Typing module types**

- `typing.Any`
- `typing.Optional`
- `typing.Union`
- `typing.Literal`
- `typing.NewType`
- `typing.Final`
- `typing.TypeAliasType`
- `typing.TypeAlias`
- `typing.NamedTuple` / `collections.namedtuple`
- `typing.TypedDict`
- `typing.Generic`
- `typing.TypeVar`

**Abstract types**

- `collections.abc.Collection` / `typing.Collection`
- `collections.abc.Sequence` / `typing.Sequence`
- `collections.abc.MutableSequence` / `typing.MutableSequence`
- `collections.abc.Set` / `typing.AbstractSet`
- `collections.abc.MutableSet` / `typing.MutableSet`
- `collections.abc.Mapping` / `typing.Mapping`
- `collections.abc.MutableMapping` / `typing.MutableMapping`

**Third-Party Libraries**

- attrs_ types

Additional types may be supported through :doc:`extensions <extending>`.

Note that except where explicitly stated, subclasses of these types are not
supported by default (see :doc:`extending` for how to add support yourself).

Here we document how msgspec maps Python objects to/from the various supported
protocols.

``None``
--------

`None` maps to the ``null`` value in all supported protocols. Note that TOML_
lacks a ``null`` value, attempted to encode a message containing ``None`` to
``TOML`` will result in an error.

.. code-block:: python

    >>> msgspec.json.encode(None)
    b'null'

    >>> msgspec.json.decode(b'null')
    None

If ``strict=False`` is specified, a string value of ``"null"`` (case
insensitive) may also be coerced to ``None``. See :ref:`strict-vs-lax` for more
information.

.. code-block:: python

   >>> msgspec.json.decode(b'"null"', type=None, strict=False)
   None

``bool``
--------

Booleans map to their corresponding ``true``/``false`` values in both all
supported protocols.

.. code-block:: python

    >>> msgspec.json.encode(True)
    b'true'

    >>> msgspec.json.decode(b'true')
    True

If ``strict=False`` is specified, values of ``"true"``/``"1"``/``1`` or
``"false"``/``"0"``/``0`` (case insensitive for strings) may also be coerced to
``True``/``False`` respectively. See :ref:`strict-vs-lax` for more information.

.. code-block:: python

   >>> msgspec.json.decode(b'"false"', type=bool, strict=False)
   False

   >>> msgspec.json.decode(b'"TRUE"', type=bool, strict=False)
   True

   >>> msgspec.json.decode(b'1', type=bool, strict=False)
   True

``int``
-------

Integers map to integers in all supported protocols.

Support for large integers varies by protocol:

- ``msgpack`` only supports encoding/decoding integers within
  ``[-2**63, 2**64 - 1]``, inclusive.
- ``json``, ``yaml``, and ``toml`` have no restrictions on encode or decode.

.. code-block:: python

    >>> msgspec.json.encode(123)
    b"123"

    >>> msgspec.json.decode(b"123", type=int)
    123

If ``strict=False`` is specified, string values may also be coerced to
integers, following the same restrictions as above. Likewise floats that have
an exact integer representation (i.e. no decimal component) may also be coerced
as integers. See :ref:`strict-vs-lax` for more information.

.. code-block:: python

   >>> msgspec.json.decode(b'"123"', type=int, strict=False)
   123

   >>> msgspec.json.decode(b'123.0', type=int, strict=False)
   123


``float``
---------

Floats map to floats in all supported protocols. Note that per RFC8259_, JSON
doesn't support nonfinite numbers (``nan``, ``infinity``, ``-infinity``);
``msgspec.json`` handles this by encoding these values as ``null``. The
``msgpack``, ``toml``, and ``yaml`` protocols lack this restriction, and can
accurately roundtrip any IEEE754 64 bit floating point value.

For all protocols, if a `float` type is specified and an `int` value is
provided, the `int` will be automatically converted.

.. code-block:: python

    >>> msgspec.json.encode(123.0)
    b"123.0"

    >>> # JSON doesn't support nonfinite values, these serialize as null
    ... msgspec.json.encode(float("nan"))
    b"null"

    >>> msgspec.json.decode(b"123.0", type=float)
    123.0

    >>> # Ints are automatically converted to floats
    ... msgspec.json.decode(b"123", type=float)
    123.0

If ``strict=False`` is specified, string values may also be coerced to floats.
Note that in this case the strings ``"nan"``, ``"inf"``/``"infinity"``,
``"-inf"``/``"-infinity"`` (case insensitive) will coerce to
``nan``/``inf``/``-inf``. See :ref:`strict-vs-lax` for more information.

.. code-block:: python

   >>> msgspec.json.decode(b'"123.45"', type=float, strict=False)
   123.45

   >>> msgspec.json.decode(b'"-inf"', type=float, strict=False)
   -inf

``str``
-------

Strings map to strings in all supported protocols.

Note that for JSON, only the characters required by RFC8259_ are escaped to
ascii; unicode characters (e.g. ``"𝄞"``) are *not* escaped and are serialized
directly as UTF-8 bytes.

.. code-block:: python

    >>> msgspec.json.encode("Hello, world!")
    b'"Hello, world!"'

    >>> msgspec.json.encode("𝄞 is not escaped")
    b'"\xf0\x9d\x84\x9e is not escaped"'

    >>> msgspec.json.decode(b'"Hello, world!"')
    "Hello, world!"

``bytes`` / ``bytearray`` / ``memoryview``
------------------------------------------

Bytes-like objects map to base64-encoded strings in JSON, YAML, and TOML. The
``bin`` type is used for MessagePack.

.. code-block:: python

    >>> msg = msgspec.json.encode(b"\xf0\x9d\x84\x9e")

    >>> msg
    b'"85+Eng=="'

    >>> msgspec.json.decode(msg, type=bytes)
    b'\xf0\x9d\x84\x9e'

    >>> msgspec.json.decode(msg, type=bytearray)
    bytearray(b'\xf0\x9d\x84\x9e')


.. note::

    For the ``msgpack`` protocol, `memoryview` objects will be decoded as
    direct views into the larger buffer containing the input message being
    decoded. This may be useful for implementing efficient zero-copy handling
    of large binary messages, but is also a potential footgun. As long as a
    decoded ``memoryview`` remains in memory, the input message buffer will
    also be persisted, potentially resulting in unnecessarily large memory
    usage. The usage of ``memoryview`` types in this manner is considered an
    advanced topic, and should only be used when you know their usage will
    result in a performance benefit.

    For all other protocols `memoryview` objects will still result in a copy,
    and will likely be slightly slower than decoding into a `bytes` object


``datetime``
------------

The encoding used for `datetime.datetime` objects depends on both the
protocol and whether these objects are timezone-aware_ or timezone-naive:

- **JSON**: Timezone-aware datetimes are encoded as RFC3339_ compatible
  strings. Timezone-naive datetimes are encoded the same, but lack the timezone
  component (making them not strictly RFC3339_ compatible, but still ISO8601_
  compatible).

- **MessagePack**: Timezone-aware datetimes are encoded using the `timestamp
  extension`. Timezone-naive datetimes are encoded the same, but lack the
  timezone component (making them not strictly RFC3339_ compatible, but still
  ISO8601_ compatible). During decoding, both string and timestamp-extension
  values are supported for flexibility.

- **YAML**: Datetimes are encoded using YAML's native datetime type. Both
  timezone-aware and timezone-naive datetimes are supported.

- **TOML**: Datetimes are encoded using TOML's native datetime type. Both
  timezone-aware and timezone-naive datetimes are supported.

Note that you can require a `datetime.datetime` object to be timezone-aware or
timezone-naive by specifying a ``tz`` constraint (see
:ref:`datetime-constraints` for more information).

.. code-block:: python

    >>> import datetime

    >>> tz = datetime.timezone(datetime.timedelta(hours=6))

    >>> tz_aware = datetime.datetime(2021, 4, 2, 18, 18, 10, 123, tzinfo=tz)

    >>> msg = msgspec.json.encode(tz_aware)

    >>> msg
    b'"2021-04-02T18:18:10.000123+06:00"'

    >>> msgspec.json.decode(msg, type=datetime.datetime)
    datetime.datetime(2021, 4, 2, 18, 18, 10, 123, tzinfo=datetime.timezone(datetime.timedelta(seconds=21600)))

    >>> tz_naive = datetime.datetime(2021, 4, 2, 18, 18, 10, 123)

    >>> msg = msgspec.json.encode(tz_naive)

    >>> msg
    b'"2021-04-02T18:18:10.000123"'

    >>> msgspec.json.decode(msg, type=datetime.datetime)
    datetime.datetime(2021, 4, 2, 18, 18, 10, 123)

    >>> msgspec.json.decode(b'"oops"', type=datetime.datetime)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Invalid RFC3339 encoded datetime


Additionally, if ``strict=False`` is specified, all protocols will decode ints,
floats, or strings containing ints/floats as timezone-aware datetimes,
interpreting the value as seconds since the epoch in UTC (a `Unix Timestamp
<https://en.wikipedia.org/wiki/Unix_time>`__). See :ref:`strict-vs-lax` for
more information.

.. code-block:: python

    >>> msgspec.json.decode(b"1617405490.000123", type=datetime.datetime)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `datetime`, got `float`

    >>> msgspec.json.decode(b"1617405490.000123", type=datetime.datetime, strict=False)
    datetime.datetime(2021, 4, 2, 18, 18, 10, 123, tzinfo=datetime.timezone.utc)

``date``
--------

`datetime.date` values map to:

- **JSON**: RFC3339_ encoded strings
- **MessagePack**: RFC3339_ encoded strings
- **YAML**: YAML's native date type
- **TOML** TOML's native date type

.. code-block:: python

    >>> import datetime

    >>> date = datetime.date(2021, 4, 2)

    >>> msg = msgspec.json.encode(date)

    >>> msg
    b'"2021-04-02"'

    >>> msgspec.json.decode(msg, type=datetime.date)
    datetime.date(2021, 4, 2)

    >>> msgspec.json.decode(b'"oops"', type=datetime.date)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Invalid RFC3339 encoded date

``time``
--------

The encoding used for `datetime.time` objects is dependent on both the protocol
and whether these objects are timezone-aware_ or timezone-naive:

- **JSON**, **MessagePack**, and **YAML**: Timezone-aware times are encoded as
  RFC3339_ compatible strings. Timezone-naive times are encoded the same, but
  lack the timezone component (making them not strictly RFC3339_ compatible,
  but still ISO8601_ compatible).

- **TOML**: Timezone-naive times are encoded using TOML's native time type.
  Timezone-aware times aren't supported.

Note that you can require a `datetime.time` object to be timezone-aware or
timezone-naive by specifying a ``tz`` constraint (see
:ref:`datetime-constraints` for more information).

.. code-block:: python

    >>> import datetime

    >>> tz = datetime.timezone(datetime.timedelta(hours=6))

    >>> tz_aware = datetime.time(18, 18, 10, 123, tzinfo=tz)

    >>> msg = msgspec.json.encode(tz_aware)

    >>> msg
    b'"18:18:10.000123+06:00"'

    >>> msgspec.json.decode(msg, type=datetime.time)
    datetime.time(18, 18, 10, 123, tzinfo=datetime.timezone(datetime.timedelta(seconds=21600)))

    >>> tz_naive = datetime.time(18, 18, 10, 123)

    >>> msg = msgspec.json.encode(tz_naive)

    >>> msg
    b'"18:18:10.000123"'

    >>> msgspec.json.decode(msg, type=datetime.time)
    datetime.time(18, 18, 10, 123)

    >>> msgspec.json.decode(b'"oops"', type=datetime.time)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Invalid RFC3339 encoded time

``timedelta``
-------------

`datetime.timedelta` values map to extended `ISO 8601 duration strings`_ in all
protocols.

The format as described in the ISO specification is fairly lax and a bit
underspecified, leading most real-world implementations to implement a stricter
subset.

The duration format used here is as follows:

.. code-block:: text

   [+/-]P[#D][T[#H][#M][#S]]

- The format starts with an optional sign (``-`` or ``+``). If negative, the
  whole duration is negated.

- The letter ``P`` follows (case insensitive)

- There are then four segments, each consisting of a number and unit. The units
  are ``D``, ``H``, ``M``, ``S`` (case insensitive) for days, hours, minutes,
  and seconds respectively. These segments must occur in this order.

  - If a segment would have a 0 value it may be omitted, with the caveat that at
    least one segment must be present.

  - If a time (hour, minute, or second) segment is present then the letter ``T``
    (case insensitive) must precede the first time segment. Likewise if a ``T``
    is present, there must be at least 1 segment after the ``T``.

  - Each segment is composed of 1 or more digits, followed by the unit. Leading
    0s are accepted. The *final* segment may include a decimal component if
    needed.

A few examples:

.. code-block:: python

   "P0D"                # 0 days
   "P1D"                # 1 Day
   "PT1H30S"            # 1 Hour and 30 minutes
   "PT1.5H"             # 1 Hour and 30 minutes
   "-PT1M30S"           # -90 seconds
   "PT1H30M25.5S"       # 1 Hour, 30 minutes, and 25.5 seconds

While msgspec will decode duration strings making use of the ``H`` (hour) or
``M`` (minute) units, durations encoded by msgspec will only consist of ``D``
(day) and ``S`` (second) segments.

The implementation in ``msgspec`` is compatible with the ones in:

- Java's ``time.Duration.parse`` (`docs <https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/Duration.html#parse(java.lang.CharSequence)>`__)
- Javascript's proposed ``Temporal.Duration`` standard API (`docs <https://tc39.es/proposal-temporal/docs/duration.html>`__)
- Python libraries like pendulum_ or pydantic_.

Duration strings produced by msgspec should be interchangeable with these
libraries, as well as similar ones in other language ecosystems.

.. code-block:: python

    >>> from datetime import timedelta

    >>> msgspec.json.encode(timedelta(seconds=123))
    b'"PT123S"'

    >>> msgspec.json.encode(timedelta(days=1, seconds=30, microseconds=123))
    b'"P1DT30.000123S"'

    >>> msgspec.json.decode(b'"PT123S"', type=timedelta)
    datetime.timedelta(seconds=123)

    >>> msgspec.json.decode(b'"PT1.5M"', type=timedelta)
    datetime.timedelta(seconds=90)

    >>> msgspec.json.decode(b'"oops"', type=datetime.timedelta)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Invalid ISO8601 duration

Additionally, if ``strict=False`` is specified, all protocols will decode ints,
floats, or strings containing ints/floats as timedeltas, interpreting the value
as total seconds. See :ref:`strict-vs-lax` for more information.

.. code-block:: python

    >>> msgspec.json.decode(b"123.4", type=datetime.timedelta)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `duration`, got `float`

    >>> msgspec.json.decode(b"123.4", type=datetime.timedelta, strict=False)
    datetime.timedelta(seconds=123, microseconds=400000)

``uuid``
--------

`uuid.UUID` values are serialized as RFC4122_ encoded canonical strings in all
protocols by default. Subclasses of `uuid.UUID` are also supported for encoding
only.

.. code-block:: python

    >>> import uuid

    >>> u = uuid.UUID("c4524ac0-e81e-4aa8-a595-0aec605a659a")

    >>> msgspec.json.encode(u)
    b'"c4524ac0-e81e-4aa8-a595-0aec605a659a"'

    >>> msgspec.json.decode(b'"c4524ac0-e81e-4aa8-a595-0aec605a659a"', type=uuid.UUID)
    UUID('c4524ac0-e81e-4aa8-a595-0aec605a659a')

    >>> msgspec.json.decode(b'"oops"', type=uuid.UUID)
    Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Invalid UUID

Alternative formats are also supported by the JSON and MessagePack encoders.
The format may be selected by passing it to ``uuid_format`` when creating an
``Encoder``. The following options are supported:

- ``canonical``: UUIDs are encoded as RFC4122_ canonical strings (same as
  ``str(uuid)``). This is the default.
- ``hex``: UUIDs are encoded as RFC4122_ hex strings (same as ``uuid.hex``).
- ``bytes``: UUIDs are encoded as binary values of the uuid's big-endian
  128-bit integer representation (same as ``uuid.bytes``). This is only supported
  by the MessagePack encoder.

When decoding, any of the above formats are accepted.

.. code-block:: python

    >>> enc = msgspec.json.Encoder(uuid_format="hex")

    >>> uuid_hex = enc.encode(u)

    >>> uuid_hex
    b'"c4524ac0e81e4aa8a5950aec605a659a"'

    >>> msgspec.json.decode(uuid_hex, type=uuid.UUID)
    UUID('c4524ac0-e81e-4aa8-a595-0aec605a659a')

    >>> enc = msgspec.msgpack.Encoder(uuid_format="bytes")

    >>> uuid_bytes = enc.encode(u)

    >>> msgspec.msgpack.decode(uuid_bytes, type=uuid.UUID)
    UUID('c4524ac0-e81e-4aa8-a595-0aec605a659a')


``decimal``
-----------

`decimal.Decimal` values are encoded as their string representation in all
protocols by default. This ensures no precision loss during serialization, as
would happen with a float representation.

.. code-block:: python

    >>> import decimal

    >>> x = decimal.Decimal("1.2345")

    >>> msg = msgspec.json.encode(x)

    >>> msg
    b'"1.2345"'

    >>> msgspec.json.decode(msg, type=decimal.Decimal)
    Decimal('1.2345')

    >>> msgspec.json.decode(b'"oops"', type=decimal.Decimal)
    Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Invalid decimal string

For JSON and MessagePack you may instead encode decimal values the same as
numbers by creating a ``Encoder`` and specifying ``decimal_format='number'``.

.. code-block:: python

    >>> encoder = msgspec.json.Encoder(decimal_format="number")

    >>> encoder.encode(x)
    b'1.2345'

This setting is not yet supported for YAML or TOML - if this option is
important for you please `open an issue`_.

All protocols will also decode `decimal.Decimal` values from ``int`` or
``float`` inputs. For JSON the value is parsed directly from the serialized
bytes, avoiding any precision loss:

.. code-block:: python

   >>> msgspec.json.decode(b"1.3", type=decimal.Decimal)
   Decimal('1.3')

   >>> msgspec.json.decode(b"1.300", type=decimal.Decimal)
   Decimal('1.300')

   >>> msgspec.json.decode(b"0.1234567891234567811", type=decimal.Decimal)
   Decimal('0.1234567891234567811')

Other protocols will coerce float inputs to the shortest decimal value that
roundtrips back to the corresponding IEEE754 float representation (this is
effectively equivalent to ``decimal.Decimal(str(float_val))``). This may result
in precision loss for some inputs! In general we recommend avoiding parsing
`decimal.Decimal` values from anything but strings.

.. code-block:: python

   >>> msgspec.yaml.decode(b"1.3", type=decimal.Decimal)
   Decimal('1.3')

   >>> msgspec.yaml.decode(b"1.300", type=decimal.Decimal)  # trailing 0s truncated!
   Decimal('1.3')

   >>> msgspec.yaml.decode(b"0.1234567891234567811", type=decimal.Decimal)  # precision loss!
   Decimal('0.12345678912345678')


``list`` / ``tuple`` / ``set`` / ``frozenset``
----------------------------------------------

`list`, `tuple`, `set`, and `frozenset` objects map to arrays in all protocols.
An error is raised if the elements don't match the specified element type (if
provided).

Subclasses of these types are also supported for encoding only. To decode into
a ``list`` subclass you'll need to implement a ``dec_hook`` (see
:doc:`extending`).

.. code-block:: python

    >>> msgspec.json.encode([1, 2, 3])
    b'[1,2,3]'

    >>> msgspec.json.encode({1, 2, 3})
    b'[1,2,3]'

    >>> msgspec.json.decode(b'[1,2,3]', type=set)
    {1, 2, 3}

    >>> from typing import Set

    >>> # Decode as a set of ints
    ... msgspec.json.decode(b'[1, 2, 3]', type=Set[int])
    {1, 2, 3}

    >>> # Oops, all elements should be ints
    ... msgspec.json.decode(b'[1, 2, "oops"]', type=Set[int])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `int`, got `str` - at `$[2]`

``NamedTuple``
--------------

`typing.NamedTuple` types map to arrays in all protocols.  An error is raised
during decoding if the type doesn't match or if any required fields are
missing.

Note that ``msgspec`` supports both `typing.NamedTuple` and
`collections.namedtuple`, although the latter lacks a way to specify field
types.

When possible we recommend using `msgspec.Struct` (possibly with
``array_like=True`` and ``frozen=True``) instead of ``NamedTuple`` for
specifying schemas - :doc:`structs` are faster, more ergonomic, and support
additional features.  Still, you may want to use a ``NamedTuple`` if you're
already using them elsewhere, or if you have downstream code that requires a
``tuple`` instead of an object.

.. code-block:: python

    >>> from typing import NamedTuple

    >>> class Person(NamedTuple):
    ...     name: str
    ...     age: int

    >>> ben = Person("ben", 25)

    >>> msg = msgspec.json.encode(ben)

    >>> msgspec.json.decode(msg, type=Person)
    Person(name='ben', age=25)

    >>> wrong_type = b'["chad", "twenty"]'

    >>> msgspec.json.decode(wrong_type, type=Person)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `int`, got `str` - at `$[1]`

Other types that duck-type as ``NamedTuple`` (for example
`edgedb NamedTuples <https://www.edgedb.com/docs/clients/python/api/types#named-tuples>`__)
are also supported.

.. code-block:: python

    >>> import edgedb

    >>> client = edgedb.create_client()

    >>> alice = client.query_single(
    ...     "SELECT (name := 'Alice', dob := <cal::local_date>'1984-03-01')"
    ... )

    >>> alice
    (name := 'Alice', dob := datetime.date(1984, 3, 1))

    >>> msgspec.json.encode(alice)
    b'["Alice","1984-03-01"]'

``dict``
--------

Dicts encode/decode as objects/maps in all protocols.

Dict subclasses (`collections.OrderedDict`, for example) are also supported for
encoding only. To decode into a ``dict`` subclass you'll need to implement a
``dec_hook`` (see :doc:`extending`).

JSON and TOML only support key types that encode as strings or numbers (for
example `str`, `int`, `float`, `enum.Enum`, `datetime.datetime`, `uuid.UUID`,
...). MessagePack and YAML support any hashable for the key type.

An error is raised during decoding if the keys or values don't match their
respective types (if specified).

.. code-block:: python

    >>> msgspec.json.encode({"x": 1, "y": 2})
    b'{"x":1,"y":2}'

    >>> from typing import Dict

    >>> # Decode as a Dict of str -> int
    ... msgspec.json.decode(b'{"x":1,"y":2}', type=Dict[str, int])
    {"x": 1, "y": 2}

    >>> # Oops, there's a mistyped value
    ... msgspec.json.decode(b'{"x":1,"y":"oops"}', type=Dict[str, int])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `int`, got `str` - at `$[...]`

``TypedDict``
-------------

`typing.TypedDict` provides a way to specify different types for different
values in a ``dict``, rather than a single value type (the ``int`` in
``Dict[str, int]``, for example).  At runtime these are just standard
``dict`` types, the ``TypedDict`` type is only there to provide the schema
information during decoding. Note that ``msgspec`` supports both
`typing.TypedDict` and ``typing_extensions.TypedDict`` (a backport).

`typing.TypedDict` types map to objects/maps in all protocols. During decoding,
any extra fields are ignored. An error is raised during decoding if the type
doesn't match or if any required fields are missing.

When possible we recommend using `msgspec.Struct` instead of ``TypedDict`` for
specifying schemas - :doc:`structs` are faster, more ergonomic, and support
additional features. Still, you may want to use a ``TypedDict`` if you're
already using them elsewhere, or if you have downstream code that requires a
``dict`` instead of an object.

.. code-block:: python

    >>> from typing import TypedDict

    >>> class Person(TypedDict):
    ...     name: str
    ...     age: int

    >>> ben = {"name": "ben", "age": 25}

    >>> msg = msgspec.json.encode(ben)

    >>> msgspec.json.decode(msg, type=Person)
    {'name': 'ben', 'age': 25}

    >>> wrong_type = b'{"name": "chad", "age": "twenty"}'

    >>> msgspec.json.decode(wrong_type, type=Person)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `int`, got `str` - at `$.age`

``dataclasses``
---------------

`dataclasses` map to objects/maps in all protocols.

During decoding, any extra fields are ignored. An error is raised if a field's
type doesn't match or if any required fields are missing.

If a ``__post_init__`` method is defined on the dataclass, it is called after
the object is decoded. Note that `"Init-only parameters"
<https://docs.python.org/3/library/dataclasses.html#init-only-variables>`__
(i.e. ``InitVar`` fields) are _not_ supported.

When possible we recommend using `msgspec.Struct` instead of dataclasses for
specifying schemas - :doc:`structs` are faster, more ergonomic, and support
additional features.

.. code-block:: python

    >>> from dataclasses import dataclass

    >>> @dataclass
    ... class Person:
    ...     name: str
    ...     age: int

    >>> carol = Person(name="carol", age=32)

    >>> msg = msgspec.json.encode(carol)

    >>> msgspec.json.decode(msg, type=Person)
    Person(name='carol', age=32)

    >>> wrong_type = b'{"name": "doug", "age": "thirty"}'

    >>> msgspec.json.decode(wrong_type, type=Person)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `int`, got `str` - at `$.age`

Other types that duck-type as ``dataclasses`` (for example
`edgedb Objects <https://www.edgedb.com/docs/clients/python/api/types#objects>`__ or
`pydantic dataclasses <https://docs.pydantic.dev/latest/usage/dataclasses/>`__)
are also supported.

.. code-block:: python

    >>> import edgedb

    >>> client = edgedb.create_client()

    >>> alice = client.query_single(
    ...     "SELECT User {name, dob} FILTER .name = <str>$name LIMIT 1",
    ...     name="Alice"
    ... )

    >>> alice
    Object{name := 'Alice', dob := datetime.date(1984, 3, 1)}

    >>> msgspec.json.encode(alice)
    b'{"id":"a6b951cc-2d00-11ee-91aa-b3f17e9898ce","name":"Alice","dob":"1984-03-01"}'

For a more complete example using EdgeDB, see :doc:`examples/edgedb`.

``attrs``
---------

attrs_ types map to objects/maps in all protocols.

During encoding, all attributes without a leading underscore (``"_"``) are
encoded.

During decoding, any extra fields are ignored. An error is raised if a field's
type doesn't match or if any required fields are missing.

If the ``__attrs_pre_init__`` or ``__attrs_post_init__`` methods are defined on
the class, they are called as part of the decoding process. Likewise, if a
class makes use of attrs' `validators
<https://www.attrs.org/en/stable/examples.html#validators>`__, the validators
will be called, and a `msgspec.ValidationError` raised on error. Note that
attrs' `converters
<https://www.attrs.org/en/stable/examples.html#conversion>`__ are not currently
supported.

When possible we recommend using `msgspec.Struct` instead of attrs_ types for
specifying schemas - :doc:`structs` are faster, more ergonomic, and support
additional features.

.. code-block:: python

    >>> from attrs import define

    >>> @define
    ... class Person:
    ...     name: str
    ...     age: int

    >>> carol = Person(name="carol", age=32)

    >>> msg = msgspec.json.encode(carol)

    >>> msgspec.json.decode(msg, type=Person)
    Person(name='carol', age=32)

    >>> wrong_type = b'{"name": "doug", "age": "thirty"}'

    >>> msgspec.json.decode(wrong_type, type=Person)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `int`, got `str` - at `$.age`

``Struct``
----------

Structs are the preferred way of defining structured data types in ``msgspec``.
You can think of them as similar to dataclasses_/attrs_/pydantic_, but much
faster to create/compare/encode/decode. For more information, see the
:doc:`structs` page.

By default `msgspec.Struct` types map to objects/maps in all protocols. During
decoding, any unknown fields are ignored (this can be disabled, see
:ref:`forbid-unknown-fields`), and any missing optional fields have their
default values applied. An error is raised during decoding if the type doesn't
match or if any required fields are missing.

.. code-block:: python

    >>> from typing import Set, Optional

    >>> class User(msgspec.Struct):
    ...     name: str
    ...     groups: Set[str] = set()
    ...     email: Optional[str] = None

    >>> alice = User("alice", groups={"admin", "engineering"})

    >>> msgspec.json.encode(alice)
    b'{"name":"alice","groups":["admin","engineering"],"email":null}'

    >>> msg = b"""
    ... {
    ...     "name": "bob",
    ...     "email": "bob@company.com",
    ...     "unknown_field": [1, 2, 3]
    ... }
    ... """

    >>> msgspec.json.decode(msg, type=User)
    User(name='bob', groups=[], email="bob@company.com")

    >>> wrong_type = b"""
    ... {
    ...     "name": "bob",
    ...     "groups": ["engineering", 123]
    ... }
    ... """

    >>> msgspec.json.decode(wrong_type, type=User)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `str`, got `int` - at `$.groups[1]`

If you pass ``array_like=True`` when defining the struct type, they're instead
treated as array types during encoding/decoding. In this case fields are
serialized in their :ref:`field order <struct-field-ordering>`. This can
further improve performance at the cost of less human readable messaging. Like
``array_like=False`` (the default) structs, extra (trailing) fields are ignored
during decoding, and any missing optional fields have their defaults applied.
Type checking also still applies.

.. code-block:: python

    >>> from typing import Set, Optional

    >>> class User(msgspec.Struct, array_like=True):
    ...     name: str
    ...     groups: Set[str] = set()
    ...     email: Optional[str] = None

    >>> alice = User("alice", groups={"admin", "engineering"})

    >>> msgspec.json.encode(alice)
    b'["alice",["admin","engineering"],null]'

    >>> msgspec.json.decode(b'["bob"]', type=User)
    User(name="bob", groups=[], email=None)

    >>> msgspec.json.decode(b'["carol", ["admin"], null, ["extra", "field"]]', type=User)
    User(name="carol", groups=["admin"], email=None)

    >>> msgspec.json.decode(b'["david", ["finance", 123]]')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `str`, got `int` - at `$[1][1]`

.. _unset-type:

``UNSET``
---------

`msgspec.UNSET` is a singleton object used to indicate that a field has no set
value. This is useful for cases where you need to differentiate between a
message where a field is missing and a message where the field is explicitly
``None``.

.. code-block:: python

    >>> from msgspec import Struct, UnsetType, UNSET, json

    >>> class Example(Struct):
    ...     x: int
    ...     y: int | None | UnsetType = UNSET  # a field, defaulting to UNSET

During encoding, any field containing ``UNSET`` is omitted from the message.

.. code-block:: python

    >>> json.encode(Example(1))  # y is UNSET
    b'{"x":1}'

    >>> json.encode(Example(1, UNSET))  # y is UNSET
    b'{"x":1}'

    >>> json.encode(Example(1, None))  # y is None
    b'{"x":1,"y":null}'

    >>> json.encode(Example(1, 2))  # y is 2
    b'{"x":1,"y":2}'

During decoding, if a field isn't explicitly set in the message, the default
value of ``UNSET`` will be set instead. This lets downstream consumers
determine whether a field was left unset, or explicitly set to ``None``

.. code-block:: python

    >>> json.decode(b'{"x": 1}', type=Example)  # y defaults to UNSET
    Example(x=1, y=UNSET)

    >>> json.decode(b'{"x": 1, "y": null}', type=Example)  # y is None
    Example(x=1, y=None)

    >>> json.decode(b'{"x": 1, "y": 2}', type=Example)  # y is 2
    Example(x=1, y=2)

``UNSET`` fields are supported for `msgspec.Struct`, `dataclasses`, and attrs_
types. It is an error to use `msgspec.UNSET` or `msgspec.UnsetType` anywhere
other than a field for one of these types.

``Enum`` / ``IntEnum`` / ``StrEnum``
------------------------------------

Enum types (`enum.Enum`, `enum.IntEnum`, `enum.StrEnum`, ...) encode as their
member *values* in all protocols.

Any enum whose *value* is a supported type may be encoded, but only enums
composed of all string or all integer values may be decoded.

An error is raised during decoding if the value isn't the proper type, or
doesn't match any valid member.

.. code-block:: python

    >>> import enum

    >>> class Fruit(enum.Enum):
    ...     APPLE = "apple"
    ...     BANANA = "banana"

    >>> msgspec.json.encode(Fruit.APPLE)
    b'"apple"'

    >>> msgspec.json.decode(b'"apple"', type=Fruit)
    <Fruit.APPLE: 'apple'>

    >>> msgspec.json.decode(b'"grape"', type=Fruit)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Invalid enum value 'grape'

    >>> class JobState(enum.IntEnum):
    ...     CREATED = 0
    ...     RUNNING = 1
    ...     SUCCEEDED = 2
    ...     FAILED = 3

    >>> msgspec.json.encode(JobState.RUNNING)
    b'1'

    >>> msgspec.json.decode(b'2', type=JobState)
    <JobState.SUCCEEDED: 2>

    >>> msgspec.json.decode(b'4', type=JobState)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Invalid enum value 4

If the enum type includes a ``_missing_`` method (`docs
<https://docs.python.org/3/library/enum.html#enum.Enum._missing_>`__), this
method will be called to handle any missing values. It should return a valid
enum member, or ``None`` if the value is invalid. One potential use case of
this is supporting case-insensitive enums:

.. code-block:: python

    >>> import enum

    >>> class Fruit(enum.Enum):
    ...     APPLE = "apple"
    ...     BANANA = "banana"
    ...
    ...     @classmethod
    ...     def _missing_(cls, name):
    ...         """Called to handle missing enum values"""
    ...         # Normalize value to lowercase
    ...         value = name.lower()
    ...         # Return valid enum value, or None if invalid
    ...         return cls._value2member_map_.get(value)

    >>> msgspec.json.decode(b'"apple"', type=Fruit)
    <Fruit.APPLE: "apple">

    >>> msgspec.json.decode(b'"ApPlE"', type=Fruit)
    <Fruit.APPLE: "apple">

    >>> msgspec.json.decode(b'"grape"', type=Fruit)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Invalid enum value 'grape'

``Literal``
-----------

`typing.Literal` types can be used to ensure that a decoded object is within a
set of valid values. An `enum.Enum` or `enum.IntEnum` can be used for the same
purpose, but with a `typing.Literal` the decoded values are literal `int` or
`str` instances rather than `enum` objects.

A literal can be composed of any of the following objects:

- `None`
- `int` values
- `str` values
- Nested `typing.Literal` types

An error is raised during decoding if the value isn't in the set of valid
values, or doesn't match any of their component types.

.. code-block:: python

    >>> from typing import Literal

    >>> msgspec.json.decode(b'1', type=Literal[1, 2, 3])
    1

    >>> msgspec.json.decode(b'"one"', type=Literal["one", "two", "three"])
    'one'

    >>> msgspec.json.decode(b'4', type=Literal[1, 2, 3])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Invalid enum value 4

    >>> msgspec.json.decode(b'"bad"', type=Literal[1, 2, 3])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `int`, got `str`

``NewType``
-----------

`typing.NewType` types are treated identically to their base type. Their
support here is purely to aid static analysis tools like mypy_ or pyright_.

.. code-block:: python

    >>> from typing import NewType

    >>> UserId = NewType("UserId", int)

    >>> msgspec.json.encode(UserId(1234))
    b'1234'

    >>> msgspec.json.decode(b'1234', type=UserId)
    1234

    >>> msgspec.json.decode(b'"oops"', type=UserId)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `int`, got `str`

Type Aliases
------------

For complex types, sometimes it can be nice to write the type once so you can
reuse it later.

.. code-block:: python

    Point = tuple[float, float]

Here ``Point`` is a "type alias" for ``tuple[float, float]`` - ``msgspec``
will substitute in ``tuple[float, float]`` whenever the ``Point`` type
is used in an annotation.

``msgspec`` supports the following equivalent forms:

.. code-block:: python

    # Using variable assignment
    Point = tuple[float, float]

    # Using variable assignment, annotated as a `TypeAlias`
    Point: TypeAlias = tuple[float, float]

    # Using Python 3.12's new `type` statement. This only works on Python 3.12+
    type Point = tuple[float, float]

To learn more about Type Aliases, see Python's `Type Alias docs here
<https://docs.python.org/3/library/typing.html#type-aliases>`__.

Generic Types
-------------

``msgspec`` supports generic types, including `user-defined generic types`_
based on any of the following types:

- `msgspec.Struct`
- `dataclasses`
- `attrs`
- `typing.TypedDict`
- `typing.NamedTuple`

Generic types may be useful for reusing common message structures.

To define a generic type:

- Define one or more type variables (`typing.TypeVar`) to parametrize your type with.
- Add `typing.Generic` as a base class when defining your type, parametrizing
  it by the relevant type variables.
- When annotating the field types, use the relevant type variables instead of
  "concrete" types anywhere you want to be generic.

For example, here we define a generic ``Paginated`` struct type for storing
extra pagination information in an API response.

.. code-block:: python

    import msgspec
    from typing import Generic, TypeVar

    # A type variable for the item type
    T = TypeVar("T")

    class Paginated(msgspec.Struct, Generic[T]):
        """A generic paginated API wrapper, parametrized by the item type."""
        page: int        # The current page number
        per_page: int    # Number of items per page
        total: int       # The total number of items found
        items: list[T]   # Items returned, up to `per_page` in length

This type is generic over the type of item contained in ``Paginated.items``.
This ``Paginated`` wrapper may then be used to decode a message containing a
specific item type by parametrizing it with that type. When processing a
generic type, the parametrized types are substituted for the type variables.

Here we define a ``User`` type, then use it to decode a paginated API response
containing a list of users:

.. code-block:: python

    class User(msgspec.Struct):
        """A user model"""
        name: str
        groups: list[str] = []

    json_str = """
    {
        "page": 1,
        "per_page": 5,
        "total": 252,
        "items": [
            {"name": "alice", "groups": ["admin"]},
            {"name": "ben"},
            {"name": "carol", "groups": ["engineering"]},
            {"name": "dan", "groups": ["hr"]},
            {"name": "ellen", "groups": ["engineering"]}
        ]
    }
    """

    # Decode a paginated response containing a list of users
    msg = msgspec.json.decode(json_str, type=Paginated[User])
    print(msg)
    #> Paginated(
    #>     page=1, per_page=5, total=252,
    #>     items=[
    #>         User(name='alice', groups=['admin']),
    #>         User(name='ben', groups=[]),
    #>         User(name='carol', groups=['engineering']),
    #>         User(name='dan', groups=['hr']),
    #>         User(name='ellen', groups=['engineering'])
    #>     ]
    #> )

If instead we wanted to decode a paginated response of another type (say
``Team``), we could do this by parametrizing ``Paginated`` with a different
type.

.. code-block:: python

    # Decode a paginated response containing a list of teams
    msgspec.json.decode(some_other_message, type=Paginated[Team])

Any unparametrized type variables will be treated as `typing.Any` when decoding.

.. code-block:: python

    # These are equivalent.
    # The unparametrized version substitutes in `Any` for `T`
    msgspec.json.decode(some_other_message, type=Paginated)
    msgspec.json.decode(some_other_message, type=Paginated[Any])

However, if an unparametrized type variable has a ``bound`` (`docs
<https://peps.python.org/pep-0484/#type-variables-with-an-upper-bound>`__),
then the bound type will be used instead.

.. code-block:: python

    from collections.abc import Sequence
    S = TypeVar("S", bound=Sequence)  # Can be any sequence type

    class Example(msgspec.Struct, Generic[S]):
        value: S

    msg = b'{"value": [1, 2, 3]}'

    # These are equivalent.
    # The unparametrized version substitutes in `Sequence` for `S`
    msgspec.json.decode(some_other_message, type=Example)
    msgspec.json.decode(some_other_message, type=Example[Sequence])

See the official Python docs on `generic types`_ and the `corresponding PEP
<https://peps.python.org/pep-0484/#generics>`__ for more information.

Abstract Types
--------------

``msgspec`` supports several "abstract" types, decoding them as
instances of their most common concrete type.

**Decoded as lists**

- `collections.abc.Collection` / `typing.Collection`
- `collections.abc.Sequence` / `typing.Sequence`
- `collections.abc.MutableSequence` / `typing.MutableSequence`

**Decoded as sets**

- `collections.abc.Set` / `typing.AbstractSet`
- `collections.abc.MutableSet` / `typing.MutableSet`

**Decoded as dicts**

- `collections.abc.Mapping` / `typing.Mapping`
- `collections.abc.MutableMapping` / `typing.MutableMapping`

.. code-block:: python

    >>> from typing import MutableMapping

    >>> msgspec.json.decode(b'{"x": 1}', type=MutableMapping[str, int])
    {"x": 1}

    >>> msgspec.json.decode(b'{"x": "oops"}', type=MutableMapping[str, int])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `int`, got `str` - at `$[...]`

``Union`` /  ``Optional``
-------------------------

Type unions are supported, with a few restrictions. These restrictions are in
place to remove any ambiguity during decoding - given an encoded value there
must always be a single type in a given `typing.Union` that can decode that
value.

Union restrictions are as follows:

- Unions may contain at most one type that encodes to an integer (`int`,
  `enum.IntEnum`)

- Unions may contain at most one type that encodes to a string (`str`,
  `enum.Enum`, `bytes`, `bytearray`, `datetime.datetime`, `datetime.date`,
  `datetime.time`, `uuid.UUID`, `decimal.Decimal`). Note that this restriction
  is fixable with some work, if this is a feature you need please `open an issue`_.

- Unions may contain at most one type that encodes to an object (`dict`,
  `typing.TypedDict`, dataclasses_, attrs_, `Struct` with ``array_like=False``)

- Unions may contain at most one type that encodes to an array (`list`,
  `tuple`, `set`, `frozenset`, `typing.NamedTuple`, `Struct` with
  ``array_like=True``).

- Unions may contain at most one *untagged* `Struct` type. Unions containing
  multiple struct types are only supported through :ref:`struct-tagged-unions`.

- Unions with custom types are unsupported beyond optionality (i.e.
  ``Optional[CustomType]``)

.. code-block:: python

    >>> from typing import Union, List

    >>> # A decoder expecting either an int, a str, or a list of strings
    ... decoder = msgspec.json.Decoder(Union[int, str, List[str]])

    >>> decoder.decode(b'1')
    1

    >>> decoder.decode(b'"two"')
    "two"

    >>> decoder.decode(b'["three", "four"]')
    ["three", "four"]

    >>> decoder.decode(b'false')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    msgspec.ValidationError: Expected `int | str | array`, got `bool`

``Raw``
-------

`msgspec.Raw` is a buffer-like type containing an already encoded messages.
They have two common uses:

**1. Avoiding unnecessary encoding cost**

Wrapping an already encoded buffer in `msgspec.Raw` lets the encoder avoid
re-encoding the message, instead it will simply be copied to the output buffer.
This can be useful when part of a message already exists in an encoded format
(e.g. reading JSON bytes from a database and returning them as part of a larger
message).

.. code-block:: python

    >>> import msgspec

    >>> # Create a new `Raw` object wrapping a pre-encoded message
    ... fragment = msgspec.Raw(b'{"x": 1, "y": 2}')

    >>> # Compose a larger message containing the pre-encoded fragment
    ... msg = {"a": 1, "b": fragment}

    >>> # During encoding, the raw message is efficiently copied into
    ... # the output buffer, avoiding any extra encoding cost
    ... msgspec.json.encode(msg)
    b'{"a":1,"b":{"x": 1, "y": 2}}'


**2. Delaying decoding of part of a message**

Sometimes the type of a serialized value depends on the value of other fields
in a message. ``msgspec`` provides an optimized version of one common pattern
(:ref:`struct-tagged-unions`), but if you need to do something more complicated
you may find using `msgspec.Raw` useful here.

For example, here we demonstrate how to decode a message where the type of one
field (``point``) depends on the value of another (``dimensions``).

.. code-block:: python

    >>> import msgspec

    >>> from typing import Union

    >>> class Point1D(msgspec.Struct):
    ...     x: int

    >>> class Point2D(msgspec.Struct):
    ...     x: int
    ...     y: int

    >>> class Point3D(msgspec.Struct):
    ...     x: int
    ...     y: int
    ...     z: int

    >>> class Model(msgspec.Struct):
    ...     dimensions: int
    ...     point: msgspec.Raw  # use msgspec.Raw to delay decoding the point field

    >>> def decode_point(msg: bytes) -> Union[Point1D, Point2D, Point3D]:
    ...     """A function for efficiently decoding the `point` field"""
    ...     # First decode the outer `Model` struct. Decoding of the `point`
    ...     # field is delayed, with the composite bytes stored as a `Raw` object
    ...     # on `point`.
    ...     model = msgspec.json.decode(msg, type=Model)
    ...
    ...     # Based on the value of `dimensions`, determine which type to use
    ...     # when decoding the `point` field
    ...     if model.dimensions == 1:
    ...         point_type = Point1D
    ...     elif model.dimensions == 2:
    ...         point_type = Point2D
    ...     elif model.dimensions == 3:
    ...         point_type = Point3D
    ...     else:
    ...         raise ValueError("Too many dimensions!")
    ...
    ...     # Now that we know the type of `point`, we can finish decoding it.
    ...     # Note that `Raw` objects are buffer-like, and can be passed
    ...     # directly to the `decode` method.
    ...     return msgspec.json.decode(model.point, type=point_type)

    >>> decode_point(b'{"dimensions": 2, "point": {"x": 1, "y": 2}}')
    Point2D(x=1, y=2)

    >>> decode_point(b'{"dimensions": 3, "point": {"x": 1, "y": 2, "z": 3}}')
    Point3D(x=1, y=2, z=3)


``Any``
-------

When decoding a message with `Any` type (or no type specified), encoded types
map to Python types in a protocol specific manner.

**JSON**

JSON_ types are decoded to Python types as follows:

- ``null``: `None`
- ``bool``: `bool`
- ``string``: `str`
- ``number``: `int` or `float` [#number_json]_
- ``array``: `list`
- ``object``: `dict`

.. [#number_json] Numbers are decoded as integers if they contain no decimal or
   exponent components (e.g. ``1`` but not ``1.0`` or ``1e10``). All other
   numbers decode as floats.

**MessagePack**

MessagePack_ types are decoded to Python types as follows:

- ``nil``: `None`
- ``bool``: `bool`
- ``int``: `int`
- ``float``: `float`
- ``str``: `str`
- ``bin``: `bytes`
- ``array``: `list` or `tuple` [#tuple]_
- ``map``: `dict`
- ``ext``: `msgspec.msgpack.Ext`, `datetime.datetime`, or a custom type

.. [#tuple] Tuples are only used when the array type must be hashable (e.g.
   keys in a ``dict`` or ``set``). All other array types are deserialized as lists
   by default.

**YAML**

YAML_ types are decoded to Python types as follows:

- ``null``: `None`
- ``bool``: `bool`
- ``string``: `str`
- ``int``: `int`
- ``float``: `float`
- ``array``: `list`
- ``object``: `dict`
- ``timestamp``: `datetime.datetime`
- ``date``: `datetime.date`

**TOML**

TOML_ types are decoded to Python types as follows:

- ``bool``: `bool`
- ``string``: `str`
- ``int``: `int`
- ``float``: `float`
- ``array``: `list`
- ``table``: `dict`
- ``datetime``: `datetime.datetime`
- ``date``: `datetime.date`
- ``time``: `datetime.time`


.. _type annotations: https://docs.python.org/3/library/typing.html
.. _JSON: https://json.org
.. _MessagePack: https://msgpack.org
.. _YAML: https://yaml.org
.. _TOML: https://toml.io
.. _pydantic: https://pydantic-docs.helpmanual.io/
.. _pendulum: https://pendulum.eustace.io/
.. _RFC8259: https://datatracker.ietf.org/doc/html/rfc8259
.. _RFC3339: https://datatracker.ietf.org/doc/html/rfc3339
.. _RFC4122: https://datatracker.ietf.org/doc/html/rfc4122
.. _ISO8601: https://en.wikipedia.org/wiki/ISO_8601
.. _timestamp extension: https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
.. _dataclasses: https://docs.python.org/3/library/dataclasses.html
.. _attrs: https://www.attrs.org/en/stable/index.html
.. _timezone-aware: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects
.. _mypy: https://mypy.readthedocs.io
.. _pyright: https://github.com/microsoft/pyright
.. _generic types:
.. _user-defined generic types: https://docs.python.org/3/library/typing.html#user-defined-generic-types
.. _open an issue: https://github.com/jcrist/msgspec/issues>
.. _ISO 8601 duration strings: https://en.wikipedia.org/wiki/ISO_8601#Durations