ybelkada HF Staff commited on
Commit
5844099
·
verified ·
1 Parent(s): eb7411d

Harbor format: 871 coding_baseline tasks (part 58)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-c756db832cf4/tests/source/HISTORY.md +650 -0
  2. tasks/tasksmith-c756db832cf4/tests/source/Justfile +52 -0
  3. tasks/tasksmith-c756db832cf4/tests/source/LICENSE +11 -0
  4. tasks/tasksmith-c756db832cf4/tests/source/MANIFEST.in +11 -0
  5. tasks/tasksmith-c756db832cf4/tests/source/README.md +115 -0
  6. tasks/tasksmith-c756db832cf4/tests/source/bench/__init__.py +0 -0
  7. tasks/tasksmith-c756db832cf4/tests/source/bench/test_attrs_collections.py +152 -0
  8. tasks/tasksmith-c756db832cf4/tests/source/bench/test_attrs_nested.py +136 -0
  9. tasks/tasksmith-c756db832cf4/tests/source/bench/test_attrs_primitives.py +138 -0
  10. tasks/tasksmith-c756db832cf4/tests/source/bench/test_enums.py +68 -0
  11. tasks/tasksmith-c756db832cf4/tests/source/bench/test_primitives.py +17 -0
  12. tasks/tasksmith-c756db832cf4/tests/source/bench/test_tuples.py +35 -0
  13. tasks/tasksmith-c756db832cf4/tests/source/docs/Makefile +187 -0
  14. tasks/tasksmith-c756db832cf4/tests/source/docs/_static/custom.css +106 -0
  15. tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-700.woff +0 -0
  16. tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-700.woff2 +0 -0
  17. tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-700italic.woff +0 -0
  18. tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-700italic.woff2 +0 -0
  19. tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-italic.woff +0 -0
  20. tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-italic.woff2 +0 -0
  21. tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-regular.woff +0 -0
  22. tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-regular.woff2 +0 -0
  23. tasks/tasksmith-c756db832cf4/tests/source/docs/basics.md +106 -0
  24. tasks/tasksmith-c756db832cf4/tests/source/docs/benchmarking.md +24 -0
  25. tasks/tasksmith-c756db832cf4/tests/source/docs/cattrs.gen.rst +18 -0
  26. tasks/tasksmith-c756db832cf4/tests/source/docs/cattrs.preconf.rst +90 -0
  27. tasks/tasksmith-c756db832cf4/tests/source/docs/cattrs.rst +68 -0
  28. tasks/tasksmith-c756db832cf4/tests/source/docs/cattrs.strategies.rst +7 -0
  29. tasks/tasksmith-c756db832cf4/tests/source/docs/conf.py +305 -0
  30. tasks/tasksmith-c756db832cf4/tests/source/docs/contributing.md +3 -0
  31. tasks/tasksmith-c756db832cf4/tests/source/docs/customizing.md +572 -0
  32. tasks/tasksmith-c756db832cf4/tests/source/docs/defaulthooks.md +744 -0
  33. tasks/tasksmith-c756db832cf4/tests/source/docs/history.md +3 -0
  34. tasks/tasksmith-c756db832cf4/tests/source/docs/indepth.md +122 -0
  35. tasks/tasksmith-c756db832cf4/tests/source/docs/index.md +87 -0
  36. tasks/tasksmith-c756db832cf4/tests/source/docs/make.bat +249 -0
  37. tasks/tasksmith-c756db832cf4/tests/source/docs/migrations.md +76 -0
  38. tasks/tasksmith-c756db832cf4/tests/source/docs/modules.rst +7 -0
  39. tasks/tasksmith-c756db832cf4/tests/source/docs/preconf.md +239 -0
  40. tasks/tasksmith-c756db832cf4/tests/source/docs/recipes.md +125 -0
  41. tasks/tasksmith-c756db832cf4/tests/source/docs/strategies.md +395 -0
  42. tasks/tasksmith-c756db832cf4/tests/source/docs/unions.md +132 -0
  43. tasks/tasksmith-c756db832cf4/tests/source/docs/usage.md +218 -0
  44. tasks/tasksmith-c756db832cf4/tests/source/docs/validation.md +122 -0
  45. tasks/tasksmith-c756db832cf4/tests/source/docs/why.md +105 -0
  46. tasks/tasksmith-c756db832cf4/tests/source/pyproject.toml +190 -0
  47. tasks/tasksmith-c756db832cf4/tests/source/src/cattr/__init__.py +25 -0
  48. tasks/tasksmith-c756db832cf4/tests/source/src/cattr/converters.py +8 -0
  49. tasks/tasksmith-c756db832cf4/tests/source/src/cattr/disambiguators.py +3 -0
  50. tasks/tasksmith-c756db832cf4/tests/source/src/cattr/dispatch.py +3 -0
tasks/tasksmith-c756db832cf4/tests/source/HISTORY.md ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # History
2
+
3
+ ```{currentmodule} cattrs
4
+
5
+ ```
6
+
7
+ This project adheres to [Calendar Versioning](https://calver.org/).
8
+ The first number of the version is the year.
9
+ The second number is incremented with each release, starting at 1 for each year.
10
+ The third number is for emergencies when we need to start branches for older releases.
11
+
12
+ Our backwards-compatibility policy can be found [here](https://github.com/python-attrs/cattrs/blob/main/.github/SECURITY.md).
13
+
14
+ ## NEXT
15
+
16
+ - Support the [`frozendict`](https://docs.python.org/3.15/builtins/stdtypes.html#frozendict) built-in on Python 3.15+.
17
+ ([#787](https://github.com/python-attrs/cattrs/pull/787))
18
+ - Python 3.15 is now supported and part of the test matrix.
19
+ ([#787](https://github.com/python-attrs/cattrs/pull/787))
20
+ - {meth}`BaseConverter.structure`, {meth}`BaseConverter.get_structure_hook` and the preconfigured converters' `loads` methods now use
21
+ [PEP 747](https://peps.python.org/pep-0747/) [`TypeForm`](https://typing.python.org/en/latest/spec/type-forms.html#type-forms) annotations,
22
+ allowing type checkers to infer result types for unions, literals, type aliases and other non-trivial types.
23
+ ([#786](https://github.com/python-attrs/cattrs/pull/786))
24
+
25
+ ## 26.2.1 (2026-09-26)
26
+
27
+ - Honor field renaming overrides when selecting literal discriminators for unions, so renamed union members can be structured from their serialized keys.
28
+ ([#778](https://github.com/python-attrs/cattrs/pull/778))
29
+ - Fix heterogeneous tuples and `NamedTuple`s with a member type containing a quote in its `repr`, like `tuple[Literal["a"], int]`, crashing structuring code generation with `SyntaxError`; the index note is now embedded with `repr`.
30
+ ([#777](https://github.com/python-attrs/cattrs/pull/777))
31
+ - Fix {func}`transform_error <cattrs.transform_error>` listing the extra keys of a `ForbiddenExtraKeysError` in set iteration order, which made the message differ between runs; the keys are now sorted, like the error's own `__str__` already sorts them.
32
+ ([#776](https://github.com/python-attrs/cattrs/pull/776))
33
+
34
+ ## 26.2.0 (2026-09-08)
35
+
36
+ - Fix the `msgpack` and `cbor2` converters unstructuring naive datetimes as local time, which made the serialized value depend on the timezone of the machine doing the unstructuring; naive datetimes are now assumed to be UTC, matching what the structure hooks already read back.
37
+ ([#774](https://github.com/python-attrs/cattrs/issues/774) [#775](https://github.com/python-attrs/cattrs/pull/775))
38
+ - Fix `override(rename=...)` targets containing a quote (or other characters not safe in a bare string literal) crashing code generation with `SyntaxError`; the rename key is now embedded with `repr`.
39
+ ([#771](https://github.com/python-attrs/cattrs/pull/771))
40
+ - Fix `Counter` keys not being unstructured with the key type's own hook; the single-type-arg branch passed the whole type-args tuple to the key hook lookup instead of the key type.
41
+ ([#768](https://github.com/python-attrs/cattrs/pull/768))
42
+ - Fix `create_default_dis_func <cattrs.disambiguators.create_default_dis_func>` (aka `create_uniq_field_dis_func`) failing to disambiguate valid unions depending on the order of the member classes; unique fields are now resolved iteratively to a fixpoint.
43
+ ([#230](https://github.com/python-attrs/cattrs/issues/230) [#765](https://github.com/python-attrs/cattrs/pull/765))
44
+ - Support more recursive types on 3.14+ with specialized factories for [`annotationlib.ForwardRef`](https://docs.python.org/3/library/annotationlib.html#annotationlib.ForwardRef).
45
+ ([#740](https://github.com/python-attrs/cattrs/issues/740) [#741](https://github.com/python-attrs/cattrs/pull/741))
46
+ - `Converter <cattrs.Converter>` now uses specialized hook factories to generate hooks for tuples, increasing speed.
47
+ ([#737](https://github.com/python-attrs/cattrs/pull/737))
48
+ - Fix an `AttributeError` in `cattrs` internals that could be triggered by using the `include_subclasses` strategy in a `structure_hook_factory`
49
+ ([#721](https://github.com/python-attrs/cattrs/issues/721), [#722](https://github.com/python-attrs/cattrs/pull/722))
50
+ - Fix TypedDict codegen when keys contain single quotes.
51
+ ([#769](https://github.com/python-attrs/cattrs/pull/769))
52
+ - Add `CattrsError` exception type: all exceptions raised by `cattrs` inherit from this.
53
+ Literal and date-time validation raise this directly, instead of `Exception`.
54
+ ([#728](https://github.com/python-attrs/cattrs/pull/728))
55
+ - Fix the `detailed_validation` parameter being passed under the wrong name in {func}`namedtuple_dict_structure_factory <cattrs.cols.namedtuple_dict_structure_factory>`, causing it to be silently ignored.
56
+ ([#723](https://github.com/python-attrs/cattrs/pull/723))
57
+ - _cattrs_ is now autoformatted using Ruff.
58
+ ([#732](https://github.com/python-attrs/cattrs/pull/732))
59
+ - Support running the test suite without `cbor2` installed.
60
+ ([#748](https://github.com/python-attrs/cattrs/pull/748))
61
+ - The [union passthrough strategy](https://catt.rs/en/stable/strategies.html#union-passthrough) now supports PEP 695 type aliases as union members.
62
+ ([#753](https://github.com/python-attrs/cattrs/pull/753))
63
+ - {meth}`BaseConverter.register_structure_hook_factory` and {meth}`BaseConverter.register_unstructure_hook_factory` now properly return the factory when used as decorators.
64
+ ([#724](https://github.com/python-attrs/cattrs/pull/724))
65
+ - The {mod}`msgspec <cattrs.preconf.msgspec>` preconf converter now properly handles recursive classes on Python 3.14+.
66
+ ([#757](https://github.com/python-attrs/cattrs/pull/757))
67
+
68
+ ## 26.1.0 (2026-02-18)
69
+
70
+ - Add the {mod}`tomllib <cattrs.preconf.tomllib>` preconf converter.
71
+ See [here](https://catt.rs/en/latest/preconf.html#tomllib) for details.
72
+ ([#716](https://github.com/python-attrs/cattrs/pull/716))
73
+ - Customizing un/structuring of _attrs_ classes, dataclasses, TypedDicts and dict NamedTuples is now possible by using `Annotated[T, override()]` on fields.
74
+ See [here](https://catt.rs/en/stable/customizing.html#using-typing-annotated-t-override) for more details.
75
+ ([#717](https://github.com/python-attrs/cattrs/pull/717))
76
+ - Fix structuring of nested generic classes with stringified annotations.
77
+ ([#688](https://github.com/python-attrs/cattrs/pull/688))
78
+ - Python 3.9 is no longer supported, as it is end-of-life. Use previous versions on this Python version.
79
+ ([#698](https://github.com/python-attrs/cattrs/pull/698))
80
+ - Apply the attrs converter to the default value before checking if it is equal to the attribute's value, when `omit_if_default` is true and an attrs converter is specified.
81
+ ([#696](https://github.com/python-attrs/cattrs/pull/696))
82
+ - Use the optional `_value_` type hint to structure and unstructure enums if present.
83
+ ([#699](https://github.com/python-attrs/cattrs/issues/699))
84
+ - Aliases (when in use) now properly generate rename metadata in generated hooks.
85
+ ([#706](https://github.com/python-attrs/cattrs/issues/706) [#710](https://github.com/python-attrs/cattrs/pull/710))
86
+ - _cattrs_ now tracks performance using [codspeed](https://codspeed.io/python-attrs/cattrs).
87
+ ([#703](https://github.com/python-attrs/cattrs/pull/703))
88
+ - The {mod}`tomlkit <cattrs.preconf.tomlkit>` preconf converter now properly handles native `date` objects when structuring.
89
+ ([#707](https://github.com/python-attrs/cattrs/issues/707) [#708](https://github.com/python-attrs/cattrs/pull/708))
90
+ - The {mod}`tomlkit <cattrs.preconf.tomlkit>` preconf converter now passes date objects directly to _tomlkit_ for unstructuring.
91
+ ([#707](https://github.com/python-attrs/cattrs/issues/707) [#708](https://github.com/python-attrs/cattrs/pull/708))
92
+ - Enum handling has been optimized by switching to hook factories, improving performance especially for plain enums.
93
+ ([#705](https://github.com/python-attrs/cattrs/pull/705))
94
+ - Fix {func}`cattrs.strategies.include_subclasses` when used with {func}`cattrs.strategies.configure_tagged_union` and classes using diamond inheritance.
95
+ ([#685](https://github.com/python-attrs/cattrs/issues/685) [#713](https://github.com/python-attrs/cattrs/pull/713))
96
+ - Fix {func}`cattrs.strategies.configure_tagged_union` when used with recursive type aliases.
97
+ ([#678](https://github.com/python-attrs/cattrs/issues/678) [#714](https://github.com/python-attrs/cattrs/pull/714))
98
+
99
+ ## 25.3.0 (2025-10-07)
100
+
101
+ - **Potentially breaking**: [Abstract sets](https://docs.python.org/3/library/collections.abc.html#collections.abc.Set) are now structured into frozensets.
102
+ This allows hashability, better immutability and is more consistent with the [`collections.abc.Set`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Set) type.
103
+ See [Migrations](https://catt.rs/en/latest/migrations.html#abstract-sets-structuring-into-frozensets) for steps to restore legacy behavior.
104
+ ([#686](https://github.com/python-attrs/cattrs/pull/686))
105
+ - Python 3.14 is now supported and part of the test matrix.
106
+ ([#653](https://github.com/python-attrs/cattrs/pull/653))
107
+ - Fix unstructuring NewTypes with the {class}`BaseConverter`.
108
+ ([#684](https://github.com/python-attrs/cattrs/pull/684))
109
+ - Make some Hypothesis tests more robust.
110
+ ([#684](https://github.com/python-attrs/cattrs/pull/684))
111
+ - {func}`cattrs.strategies.include_subclasses` now works with generic parent classes and the tagged union strategy.
112
+ ([#683](https://github.com/python-attrs/cattrs/pull/683))
113
+
114
+ ## 25.2.0 (2025-08-31)
115
+
116
+ - **Potentially breaking**: Sequences are now structured into tuples.
117
+ This allows hashability, better immutability and is more consistent with the [`collections.abc.Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence) type.
118
+ See [Migrations](https://catt.rs/en/latest/migrations.html#sequences-structuring-into-tuples) for steps to restore legacy behavior.
119
+ ([#663](https://github.com/python-attrs/cattrs/pull/663))
120
+ - Add a `use_alias` parameter to {class}`cattrs.Converter`.
121
+ {func}`cattrs.gen.make_dict_unstructure_fn_from_attrs`, {func}`cattrs.gen.make_dict_unstructure_fn`,
122
+ {func}`cattrs.gen.make_dict_structure_fn_from_attrs`, {func}`cattrs.gen.make_dict_structure_fn`
123
+ and {func}`cattrs.gen.typeddicts.make_dict_structure_fn` will use the value for the `use_alias` parameter from the given converter by default now.
124
+ If you're using these functions directly, the old behavior can be restored by passing in the desired value directly.
125
+ ([#596](https://github.com/python-attrs/cattrs/issues/596) [#660](https://github.com/python-attrs/cattrs/pull/660))
126
+ - The [union passthrough strategy](https://catt.rs/en/stable/strategies.html#union-passthrough) now by default accepts ints for unions that contain floats but not ints,
127
+ when configured to be able to handle both ints and floats.
128
+ This more closely matches the [current typing behavior](https://typing.python.org/en/latest/spec/special-types.html#special-cases-for-float-and-complex).
129
+ ([#656](https://github.com/python-attrs/cattrs/issues/656) [#668](https://github.com/python-attrs/cattrs/pull/668))
130
+ - Fix unstructuring of generic classes with stringified annotations.
131
+ ([#661](https://github.com/python-attrs/cattrs/issues/661) [#662](https://github.com/python-attrs/cattrs/issues/662)
132
+ - For {class}`cattrs.errors.StructureHandlerNotFoundError` and {class}`cattrs.errors.ForbiddenExtraKeysError`
133
+ correctly set {attr}`BaseException.args` in `super()` and hence make them pickable.
134
+ ([#666](https://github.com/python-attrs/cattrs/pull/666))
135
+ - The default disambiguation hook factory is now only enabled for converters with `unstructure_strat=AS_DICT` (the default).
136
+ Since the strategy doesn't support tuples, it is skipped for `unstructure_strat=AS_TUPLE` converters.
137
+ ([#673](https://github.com/python-attrs/cattrs/pull/673))
138
+ - Switch to [`uv`](https://docs.astral.sh/uv/) and [`just`](https://just.systems/man/en/) in lieu of PDM, tox and Make.
139
+ See [the Contributing section](https://catt.rs/en/v25.2.0/contributing.html#get-started) for new workflow instructions.
140
+ ([#671](https://github.com/python-attrs/cattrs/pull/671))
141
+
142
+ ## 25.1.1 (2025-06-04)
143
+
144
+ - Fixed `AttributeError: no attribute '__parameters__'` while structuring attrs classes that inherit from parametrized generic aliases from `collections.abc`.
145
+ ([#654](https://github.com/python-attrs/cattrs/issues/654) [#655](https://github.com/python-attrs/cattrs/pull/655))
146
+
147
+ ## 25.1.0 (2025-05-31)
148
+
149
+ - **Potentially breaking**: The converters raise {class}`StructureHandlerNotFoundError` more eagerly (on hook creation, instead of on hook use).
150
+ This helps surfacing problems with missing hooks sooner.
151
+ See [Migrations](https://catt.rs/en/latest/migrations.html#the-default-structure-hook-fallback-factory) for steps to restore legacy behavior.
152
+ ([#577](https://github.com/python-attrs/cattrs/pull/577))
153
+ - Add a [Migrations](https://catt.rs/en/latest/migrations.html) page, with instructions on migrating changed behavior for each version.
154
+ ([#577](https://github.com/python-attrs/cattrs/pull/577))
155
+ - [`typing.Self`](https://docs.python.org/3/library/typing.html#typing.Self) is now supported in _attrs_ classes, dataclasses, TypedDicts and the dict NamedTuple factories.
156
+ See [`typing.Self`](https://catt.rs/en/latest/defaulthooks.html#typing-self) for details.
157
+ ([#299](https://github.com/python-attrs/cattrs/issues/299) [#627](https://github.com/python-attrs/cattrs/pull/627))
158
+ - PEP 695 type aliases can now be used with {meth}`BaseConverter.register_structure_hook` and {meth}`BaseConverter.register_unstructure_hook`.
159
+ Previously, they required the use of {meth}`BaseConverter.register_structure_hook_func` (which is still supported).
160
+ ([#647](https://github.com/python-attrs/cattrs/pull/647))
161
+ - Expose {func}`cattrs.cols.mapping_unstructure_factory` through {mod}`cattrs.cols`.
162
+ - Some `defaultdicts` are now [supported by default](https://catt.rs/en/latest/defaulthooks.html#defaultdicts), and
163
+ {func}`cattrs.cols.is_defaultdict` and {func}`cattrs.cols.defaultdict_structure_factory` are exposed through {mod}`cattrs.cols`.
164
+ ([#519](https://github.com/python-attrs/cattrs/issues/519) [#588](https://github.com/python-attrs/cattrs/pull/588))
165
+ - Generic PEP 695 type aliases are now supported.
166
+ ([#611](https://github.com/python-attrs/cattrs/issues/611) [#618](https://github.com/python-attrs/cattrs/pull/618))
167
+ - The [tagged union strategy](https://catt.rs/en/stable/strategies.html#tagged-unions-strategy) now also supports type aliases of unions.
168
+ ([#649](https://github.com/python-attrs/cattrs/pull/649))
169
+ - {meth}`Converter.copy` and {meth}`BaseConverter.copy` are correctly annotated as returning `Self`.
170
+ ([#644](https://github.com/python-attrs/cattrs/pull/644))
171
+ - Many preconf converters (_bson_, stdlib JSON, _cbor2_, _msgpack_, _msgspec_, _orjson_, _ujson_) skip unstructuring `int` and `str` enums,
172
+ leaving them to the underlying libraries to handle with greater efficiency.
173
+ ([#598](https://github.com/python-attrs/cattrs/pull/598))
174
+ - The {class}`msgspec JSON preconf converter <cattrs.preconf.msgspec.MsgspecJsonConverter>` now handles dataclasses with private attributes more efficiently.
175
+ ([#624](https://github.com/python-attrs/cattrs/pull/624))
176
+ - Literals containing enums are now unstructured properly, and their unstructuring is greatly optimized in the _bson_, stdlib JSON, _cbor2_, _msgpack_, _msgspec_, _orjson_ and _ujson_ preconf converters.
177
+ ([#598](https://github.com/python-attrs/cattrs/pull/598))
178
+ - Preconf converters now handle dictionaries with literal keys properly.
179
+ ([#599](https://github.com/python-attrs/cattrs/pull/599))
180
+ - Structuring TypedDicts from invalid inputs now properly raises a {class}`ClassValidationError`.
181
+ ([#615](https://github.com/python-attrs/cattrs/issues/615) [#616](https://github.com/python-attrs/cattrs/pull/616))
182
+ - {func}`cattrs.strategies.include_subclasses` now properly works with generic parent classes.
183
+ ([#649](https://github.com/python-attrs/cattrs/pull/650))
184
+ - Replace `cattrs.gen.MappingStructureFn` with {class}`cattrs.SimpleStructureHook`.
185
+ - Python 3.13 is now supported.
186
+ ([#543](https://github.com/python-attrs/cattrs/pull/543) [#547](https://github.com/python-attrs/cattrs/issues/547))
187
+ - Python 3.8 is no longer supported, as it is end-of-life. Use previous versions on this Python version.
188
+ ([#591](https://github.com/python-attrs/cattrs/pull/591))
189
+ - Change type of `Converter.__init__.unstruct_collection_overrides` from `Callable` to `Mapping[type, UnstructureHook]`
190
+ ([#594](https://github.com/python-attrs/cattrs/pull/594)).
191
+ - Adopt the Contributor Covenant Code of Conduct (just like _attrs_).
192
+
193
+ ## 24.1.3 (2025-03-25)
194
+
195
+ - Fix structuring of keyword-only dataclass fields when not using detailed validation.
196
+ ([#637](https://github.com/python-attrs/cattrs/issues/637) [#638](https://github.com/python-attrs/cattrs/pull/638))
197
+
198
+ ## 24.1.2 (2024-09-22)
199
+
200
+ - Fix {meth}`BaseConverter.register_structure_hook` and {meth}`BaseConverter.register_unstructure_hook` type hints.
201
+ ([#581](https://github.com/python-attrs/cattrs/issues/581) [#582](https://github.com/python-attrs/cattrs/pull/582))
202
+
203
+ ## 24.1.1 (2024-09-11)
204
+
205
+ - Fix {meth}`BaseConverter.register_structure_hook_factory` and {meth}`BaseConverter.register_unstructure_hook_factory` type hints.
206
+ ([#578](https://github.com/python-attrs/cattrs/issues/578) [#579](https://github.com/python-attrs/cattrs/pull/579))
207
+
208
+ ## 24.1.0 (2024-08-28)
209
+
210
+ - **Potentially breaking**: Unstructuring hooks for `typing.Any` are consistent now: values are unstructured using their runtime type.
211
+ Previously this behavior was underspecified and inconsistent, but followed this rule in the majority of cases.
212
+ Reverting old behavior is very dependent on the actual case; ask on the issue tracker if in doubt.
213
+ ([#473](https://github.com/python-attrs/cattrs/pull/473))
214
+ - **Minor change**: Heterogeneous tuples are now unstructured into tuples instead of lists by default; this is significantly faster and widely supported by serialization libraries.
215
+ ([#486](https://github.com/python-attrs/cattrs/pull/486))
216
+ - **Minor change**: {func}`cattrs.gen.make_dict_structure_fn` will use the value for the `prefer_attrib_converters` parameter from the given converter by default now.
217
+ If you're using this function directly, the old behavior can be restored by passing in the desired values explicitly.
218
+ ([#527](https://github.com/python-attrs/cattrs/issues/527) [#528](https://github.com/python-attrs/cattrs/pull/528))
219
+ - Introduce {meth}`BaseConverter.get_structure_hook` and {meth}`BaseConverter.get_unstructure_hook` methods.
220
+ ([#432](https://github.com/python-attrs/cattrs/issues/432) [#472](https://github.com/python-attrs/cattrs/pull/472))
221
+ - {meth}`BaseConverter.register_structure_hook`, {meth}`BaseConverter.register_unstructure_hook`,
222
+ {meth}`BaseConverter.register_unstructure_hook_factory` and {meth}`BaseConverter.register_structure_hook_factory`
223
+ can now be used as decorators and have gained new features.
224
+ See [here](https://catt.rs/en/latest/customizing.html#use-as-decorators) and [here](https://catt.rs/en/latest/customizing.html#id1) for more details.
225
+ ([#487](https://github.com/python-attrs/cattrs/pull/487))
226
+ - Introduce and [document](https://catt.rs/en/latest/customizing.html#customizing-collections) the {mod}`cattrs.cols` module for better collection customizations.
227
+ ([#504](https://github.com/python-attrs/cattrs/issues/504) [#540](https://github.com/python-attrs/cattrs/pull/540))
228
+ - Enhance the {func}`cattrs.cols.is_mapping` predicate function to also cover virtual subclasses of `abc.Mapping`.
229
+ This enables map classes from libraries such as _immutables_ or _sortedcontainers_ to structure out-of-the-box.
230
+ ([#555](https://github.com/python-attrs/cattrs/issues/555) [#556](https://github.com/python-attrs/cattrs/pull/556))
231
+ - Introduce the [_msgspec_](https://jcristharif.com/msgspec/) {mod}`preconf converter <cattrs.preconf.msgspec>`.
232
+ Only JSON is supported for now, with other formats supported by _msgspec_ to come later.
233
+ ([#481](https://github.com/python-attrs/cattrs/pull/481))
234
+ - The default union handler now properly takes renamed fields into account.
235
+ ([#472](https://github.com/python-attrs/cattrs/pull/472))
236
+ - The default union handler now also handles dataclasses.
237
+ ([#426](https://github.com/python-attrs/cattrs/issues/426) [#477](https://github.com/python-attrs/cattrs/pull/477))
238
+ - Add support for [PEP 695](https://peps.python.org/pep-0695/) type aliases.
239
+ ([#452](https://github.com/python-attrs/cattrs/pull/452))
240
+ - Add support for [PEP 696](https://peps.python.org/pep-0696/) `TypeVar`s with defaults.
241
+ ([#512](https://github.com/python-attrs/cattrs/pull/512))
242
+ - Add support for named tuples with type metadata ([`typing.NamedTuple`](https://docs.python.org/3/library/typing.html#typing.NamedTuple)).
243
+ ([#425](https://github.com/python-attrs/cattrs/issues/425) [#491](https://github.com/python-attrs/cattrs/pull/491))
244
+ - Add support for optionally un/unstructuring named tuples using dictionaries.
245
+ ([#425](https://github.com/python-attrs/cattrs/issues/425) [#549](https://github.com/python-attrs/cattrs/pull/549))
246
+ - The `include_subclasses` strategy now fetches the member hooks from the converter (making use of converter defaults) if overrides are not provided, instead of generating new hooks with no overrides.
247
+ ([#429](https://github.com/python-attrs/cattrs/issues/429) [#472](https://github.com/python-attrs/cattrs/pull/472))
248
+ - The preconf `make_converter` factories are now correctly typed.
249
+ ([#481](https://github.com/python-attrs/cattrs/pull/481))
250
+ - The {class}`orjson preconf converter <cattrs.preconf.orjson.OrjsonConverter>` now passes through dates and datetimes to orjson while unstructuring, greatly improving speed.
251
+ ([#463](https://github.com/python-attrs/cattrs/pull/463))
252
+ - {mod}`cattrs.gen` generators now attach metadata to the generated functions, making them introspectable.
253
+ ([#472](https://github.com/python-attrs/cattrs/pull/472))
254
+ - Structure hook factories in {mod}`cattrs.gen` now handle recursive classes better.
255
+ ([#540](https://github.com/python-attrs/cattrs/pull/540))
256
+ - The [tagged union strategy](https://catt.rs/en/stable/strategies.html#tagged-unions-strategy) now leaves the tags in the payload unless `forbid_extra_keys` is set.
257
+ ([#533](https://github.com/python-attrs/cattrs/issues/533) [#534](https://github.com/python-attrs/cattrs/pull/534))
258
+ - More robust support for `Annotated` and `NotRequired` in TypedDicts.
259
+ ([#450](https://github.com/python-attrs/cattrs/pull/450))
260
+ - `typing_extensions.Literal` is now automatically structured, just like `typing.Literal`.
261
+ ([#460](https://github.com/python-attrs/cattrs/issues/460) [#467](https://github.com/python-attrs/cattrs/pull/467))
262
+ - `typing_extensions.Any` is now supported and handled like `typing.Any`.
263
+ ([#488](https://github.com/python-attrs/cattrs/issues/488) [#490](https://github.com/python-attrs/cattrs/pull/490))
264
+ - `Optional` types can now be consistently customized using `register_structure_hook` and `register_unstructure_hook`.
265
+ ([#529](https://github.com/python-attrs/cattrs/issues/529) [#530](https://github.com/python-attrs/cattrs/pull/530))
266
+ - The BaseConverter now properly generates detailed validation errors for mappings.
267
+ ([#496](https://github.com/python-attrs/cattrs/pull/496))
268
+ - [PEP 695](https://peps.python.org/pep-0695/) generics are now tested.
269
+ ([#452](https://github.com/python-attrs/cattrs/pull/452))
270
+ - Imports are now sorted using Ruff.
271
+ - Tests are run with the pytest-xdist plugin by default.
272
+ - Rework the introductory parts of the documentation, introducing the Basics section.
273
+ ([#472](https://github.com/python-attrs/cattrs/pull/472))
274
+ - The documentation has been significantly reworked.
275
+ ([#473](https://github.com/python-attrs/cattrs/pull/473))
276
+ - The docs now use the Inter font.
277
+ - Make type annotations for `include_subclasses` and `tagged_union` strategies more lenient.
278
+ ([#431](https://github.com/python-attrs/cattrs/pull/431))
279
+
280
+ ## 23.2.3 (2023-11-30)
281
+
282
+ - Fix a regression when unstructuring dictionary values typed as `Any`.
283
+ ([#453](https://github.com/python-attrs/cattrs/issues/453) [#462](https://github.com/python-attrs/cattrs/pull/462))
284
+ - Fix a regression when unstructuring unspecialized generic classes.
285
+ ([#465](https://github.com/python-attrs/cattrs/issues/465) [#466](https://github.com/python-attrs/cattrs/pull/466))
286
+ - Optimize function source code caching.
287
+ ([#445](https://github.com/python-attrs/cattrs/issues/445) [#464](https://github.com/python-attrs/cattrs/pull/464))
288
+ - Generate unique files only in case of linecache enabled.
289
+ ([#445](https://github.com/python-attrs/cattrs/issues/445) [#441](https://github.com/python-attrs/cattrs/pull/461))
290
+
291
+ ## 23.2.2 (2023-11-21)
292
+
293
+ - Fix a regression when unstructuring `Any | None`.
294
+ ([#453](https://github.com/python-attrs/cattrs/issues/453) [#454](https://github.com/python-attrs/cattrs/pull/454))
295
+
296
+ ## 23.2.1 (2023-11-18)
297
+
298
+ - Fix unnecessary `typing_extensions` import on Python 3.11.
299
+ ([#446](https://github.com/python-attrs/cattrs/issues/446) [#447](https://github.com/python-attrs/cattrs/pull/447))
300
+
301
+ ## 23.2.0 (2023-11-17)
302
+
303
+ - **Potentially breaking**: skip _attrs_ fields marked as `init=False` by default. This change is potentially breaking for unstructuring.
304
+ See [here](https://catt.rs/en/latest/customizing.html#include_init_false) for instructions on how to restore the old behavior.
305
+ ([#40](https://github.com/python-attrs/cattrs/issues/40) [#395](https://github.com/python-attrs/cattrs/pull/395))
306
+ - **Potentially breaking**: {py:func}`cattrs.gen.make_dict_structure_fn` and {py:func}`cattrs.gen.typeddicts.make_dict_structure_fn` will use the values for the `detailed_validation` and `forbid_extra_keys` parameters from the given converter by default now.
307
+ If you're using these functions directly, the old behavior can be restored by passing in the desired values directly.
308
+ ([#410](https://github.com/python-attrs/cattrs/issues/410) [#411](https://github.com/python-attrs/cattrs/pull/411))
309
+ - **Potentially breaking**: The default union structuring strategy will also use fields annotated as `typing.Literal` to help guide structuring.
310
+ See [here](https://catt.rs/en/latest/unions.html#default-union-strategy) for instructions on how to restore the old behavior.
311
+ ([#391](https://github.com/python-attrs/cattrs/pull/391))
312
+ - Python 3.12 is now supported. Python 3.7 is no longer supported; use older releases there.
313
+ ([#424](https://github.com/python-attrs/cattrs/pull/424))
314
+ - Implement the `union passthrough` strategy, enabling much richer union handling for preconfigured converters. [Learn more here](https://catt.rs/en/stable/strategies.html#union-passthrough).
315
+ - Introduce the `use_class_methods` strategy. Learn more [here](https://catt.rs/en/latest/strategies.html#using-class-specific-structure-and-unstructure-methods).
316
+ ([#405](https://github.com/python-attrs/cattrs/pull/405))
317
+ - The `omit` parameter of {py:func}`cattrs.override` is now of type `bool | None` (from `bool`).
318
+ `None` is the new default and means to apply default _cattrs_ handling to the attribute, which is to omit the attribute if it's marked as `init=False`, and keep it otherwise.
319
+ - Converters can now be initialized with [custom fallback hook factories](https://catt.rs/en/latest/converters.html#fallback-hook-factories) for un/structuring.
320
+ ([#331](https://github.com/python-attrs/cattrs/issues/311) [#441](https://github.com/python-attrs/cattrs/pull/441))
321
+ - Add support for `date` to preconfigured converters.
322
+ ([#420](https://github.com/python-attrs/cattrs/pull/420))
323
+ - Add support for `datetime.date`s to the PyYAML preconfigured converter.
324
+ ([#393](https://github.com/python-attrs/cattrs/issues/393))
325
+ - Fix {py:func}`format_exception() <cattrs.v.format_exception>` parameter working for recursive calls to {py:func}`transform_error <cattrs.transform_error>`.
326
+ ([#389](https://github.com/python-attrs/cattrs/issues/389))
327
+ - [_attrs_ aliases](https://www.attrs.org/en/stable/init.html#private-attributes-and-aliases) are now supported, although aliased fields still map to their attribute name instead of their alias by default when un/structuring.
328
+ ([#322](https://github.com/python-attrs/cattrs/issues/322) [#391](https://github.com/python-attrs/cattrs/pull/391))
329
+ - Fix TypedDicts with periods in their field names.
330
+ ([#376](https://github.com/python-attrs/cattrs/issues/376) [#377](https://github.com/python-attrs/cattrs/pull/377))
331
+ - Optimize and improve unstructuring of `Optional` (unions of one type and `None`).
332
+ ([#380](https://github.com/python-attrs/cattrs/issues/380) [#381](https://github.com/python-attrs/cattrs/pull/381))
333
+ - Fix {py:func}`format_exception <cattrs.v.format_exception>` and {py:func}`transform_error <cattrs.transform_error>` type annotations.
334
+ - Improve the implementation of `cattrs._compat.is_typeddict`. The implementation is now simpler, and relies on fewer private implementation details from `typing` and typing_extensions.
335
+ ([#384](https://github.com/python-attrs/cattrs/pull/384))
336
+ - Improve handling of TypedDicts with forward references.
337
+ - Speed up generated _attrs_ and TypedDict structuring functions by changing their signature slightly.
338
+ ([#388](https://github.com/python-attrs/cattrs/pull/388))
339
+ - Fix copying of converters with function hooks.
340
+ ([#398](https://github.com/python-attrs/cattrs/issues/398) [#399](https://github.com/python-attrs/cattrs/pull/399))
341
+ - Broaden {py:func}`loads' <cattrs.preconf.orjson.OrjsonConverter.loads>` type definition for the preconf orjson converter.
342
+ ([#400](https://github.com/python-attrs/cattrs/pull/400))
343
+ - {py:class}`AttributeValidationNote <cattrs.AttributeValidationNote>` and {py:class}`IterableValidationNote <cattrs.IterableValidationNote>` are now picklable.
344
+ ([#408](https://github.com/python-attrs/cattrs/pull/408))
345
+ - Fix structuring `Final` lists.
346
+ ([#412](https://github.com/python-attrs/cattrs/issues/412))
347
+ - Fix certain cases of structuring `Annotated` types.
348
+ ([#418](https://github.com/python-attrs/cattrs/issues/418))
349
+ - Fix the [tagged union strategy](https://catt.rs/en/stable/strategies.html#tagged-unions-strategy) to work with `forbid_extra_keys`.
350
+ ([#402](https://github.com/python-attrs/cattrs/issues/402) [#443](https://github.com/python-attrs/cattrs/pull/443))
351
+ - Use [PDM](https://pdm.fming.dev/latest/) instead of Poetry.
352
+ - _cattrs_ is now linted with [Ruff](https://beta.ruff.rs/docs/).
353
+ - Remove some unused lines in the unstructuring code.
354
+ ([#416](https://github.com/python-attrs/cattrs/pull/416))
355
+ - Fix handling classes inheriting from non-generic protocols.
356
+ ([#374](https://github.com/python-attrs/cattrs/issues/374) [#436](https://github.com/python-attrs/cattrs/pull/436))
357
+ - The documentation Makefile now supports the `htmlview` and `htmllive` targets. ([#442](https://github.com/python-attrs/cattrs/pull/442))
358
+ - _cattrs_ is now published using PyPI Trusted Publishers, and `main` branch commits are automatically deployed to Test PyPI.
359
+
360
+ ## 23.1.2 (2023-06-02)
361
+
362
+ - Improve `typing_extensions` version bound. ([#372](https://github.com/python-attrs/cattrs/issues/372))
363
+
364
+ ## 23.1.1 (2023-05-30)
365
+
366
+ - Add `typing_extensions` as a direct dependency on 3.10.
367
+ ([#369](https://github.com/python-attrs/cattrs/issues/369) [#370](https://github.com/python-attrs/cattrs/pull/370))
368
+
369
+ ## 23.1.0 (2023-05-30)
370
+
371
+ - Introduce the [`tagged_union` strategy](https://catt.rs/en/stable/strategies.html#tagged-unions-strategy).
372
+ ([#318](https://github.com/python-attrs/cattrs/pull/318) [#317](https://github.com/python-attrs/cattrs/issues/317))
373
+ - Introduce the `cattrs.transform_error` helper function for formatting validation exceptions. ([258](https://github.com/python-attrs/cattrs/issues/258) [342](https://github.com/python-attrs/cattrs/pull/342))
374
+ - Add support for [`typing.TypedDict` and `typing_extensions.TypedDict`](https://peps.python.org/pep-0589/).
375
+ ([#296](https://github.com/python-attrs/cattrs/issues/296) [#364](https://github.com/python-attrs/cattrs/pull/364))
376
+ - Add support for `typing.Final`.
377
+ ([#340](https://github.com/python-attrs/cattrs/issues/340) [#349](https://github.com/python-attrs/cattrs/pull/349))
378
+ - Introduce `override.struct_hook` and `override.unstruct_hook`. Learn more [here](https://catt.rs/en/latest/customizing.html#struct-hook-and-unstruct-hook).
379
+ ([#326](https://github.com/python-attrs/cattrs/pull/326))
380
+ - Fix generating structuring functions for types with angle brackets (`<>`) and pipe symbols (`|`) in the name.
381
+ ([#319](https://github.com/python-attrs/cattrs/issues/319) [#327](https://github.com/python-attrs/cattrs/pull/327>))
382
+ - `pathlib.Path` is now supported by default.
383
+ ([#81](https://github.com/python-attrs/cattrs/issues/81))
384
+ - Add `cbor2` serialization library to the `cattrs.preconf` package.
385
+ - Add optional dependencies for `cattrs.preconf` third-party libraries. ([#337](https://github.com/python-attrs/cattrs/pull/337))
386
+ - All preconf converters now allow overriding the default `unstruct_collection_overrides` in `make_converter`.
387
+ ([#350](https://github.com/python-attrs/cattrs/issues/350) [#353](https://github.com/python-attrs/cattrs/pull/353))
388
+ - Subclasses structuring and unstructuring is now supported via a custom `include_subclasses` strategy.
389
+ ([#312](https://github.com/python-attrs/cattrs/pull/312))
390
+ - Add support for `typing_extensions.Annotated` when the python version is less than `3.9`. ([#366](https://github.com/python-attrs/cattrs/pull/366))
391
+ - Add unstructuring and structuring support for the standard library `deque`.
392
+ ([#355](https://github.com/python-attrs/cattrs/pull/355))
393
+
394
+ ## 22.2.0 (2022-10-03)
395
+
396
+ - _Potentially breaking_: `cattrs.Converter` has been renamed to `cattrs.BaseConverter`, and `cattrs.GenConverter` to `cattrs.Converter`.
397
+ The `GenConverter` name is still available for backwards compatibility, but is deprecated.
398
+ If you were depending on functionality specific to the old `Converter`, change your import to `from cattrs import BaseConverter`.
399
+ - [NewTypes](https://docs.python.org/3/library/typing.html#newtype) are now supported by the `cattrs.Converter`.
400
+ ([#255](https://github.com/python-attrs/cattrs/pull/255) [#94](https://github.com/python-attrs/cattrs/issues/94) [#297](https://github.com/python-attrs/cattrs/issues/297))
401
+ - `cattrs.Converter` and `cattrs.BaseConverter` can now copy themselves using the `copy` method.
402
+ ([#284](https://github.com/python-attrs/cattrs/pull/284))
403
+ - Python 3.11 support.
404
+ - cattrs now supports un/structuring `kw_only` fields on attrs classes into/from dictionaries.
405
+ ([#247](https://github.com/python-attrs/cattrs/pull/247))
406
+ - PyPy support (and tests, using a minimal Hypothesis profile) restored.
407
+ ([#253](https://github.com/python-attrs/cattrs/issues/253))
408
+ - Fix propagating the `detailed_validation` flag to mapping and counter structuring generators.
409
+ - Fix `typing.Set` applying too broadly when used with the `GenConverter.unstruct_collection_overrides` parameter on Python versions below 3.9. Switch to `typing.AbstractSet` on those versions to restore the old behavior.
410
+ ([#264](https://github.com/python-attrs/cattrs/issues/264))
411
+ - Uncap the required Python version, to avoid problems detailed [here](https://iscinumpy.dev/post/bound-version-constraints/#pinning-the-python-version-is-special)
412
+ ([#275](https://github.com/python-attrs/cattrs/issues/275))
413
+ - Fix `Converter.register_structure_hook_factory` and `cattrs.gen.make_dict_unstructure_fn` type annotations.
414
+ ([#281](https://github.com/python-attrs/cattrs/issues/281))
415
+ - Expose all error classes in the `cattr.errors` namespace. Note that it is deprecated, just use `cattrs.errors`.
416
+ ([#252](https://github.com/python-attrs/cattrs/issues/252))
417
+ - Fix generating structuring functions for types with quotes in the name.
418
+ ([#291](https://github.com/python-attrs/cattrs/issues/291) [#277](https://github.com/python-attrs/cattrs/issues/277))
419
+ - Fix usage of notes for the final version of [PEP 678](https://peps.python.org/pep-0678/), supported since `exceptiongroup>=1.0.0rc4`.
420
+ ([#303](https://github.com/python-attrs/cattrs/pull/303))
421
+
422
+ ## 22.1.0 (2022-04-03)
423
+
424
+ - _cattrs_ now uses the CalVer versioning convention.
425
+ - _cattrs_ now has a detailed validation mode, which is enabled by default. Learn more [here](https://cattrs.readthedocs.io/en/latest/validation.html).
426
+ The old behavior can be restored by creating the converter with `detailed_validation=False`.
427
+ - _attrs_ and dataclass structuring is now ~25% faster.
428
+ - Fix an issue structuring bare `typing.List` s on Pythons lower than 3.9.
429
+ ([#209](https://github.com/python-attrs/cattrs/issues/209))
430
+ - Fix structuring of non-parametrized containers like `list/dict/...` on Pythons lower than 3.9.
431
+ ([#218](https://github.com/python-attrs/cattrs/issues/218))
432
+ - Fix structuring bare `typing.Tuple` on Pythons lower than 3.9.
433
+ ([#218](https://github.com/python-attrs/cattrs/issues/218))
434
+ - Fix a wrong `AttributeError` of an missing `__parameters__` attribute. This could happen
435
+ when inheriting certain generic classes – for example `typing.*` classes are affected.
436
+ ([#217](https://github.com/python-attrs/cattrs/issues/217))
437
+ - Fix structuring of `enum.Enum` instances in `typing.Literal` types.
438
+ ([#231](https://github.com/python-attrs/cattrs/pull/231))
439
+ - Fix unstructuring all tuples - unannotated, variable-length, homogenous and heterogenous - to `list`.
440
+ ([#226](https://github.com/python-attrs/cattrs/issues/226))
441
+ - For `forbid_extra_keys` raise custom `ForbiddenExtraKeyError` instead of generic `Exception`.
442
+ ([#225](https://github.com/python-attrs/cattrs/pull/225))
443
+ - All preconf converters now support `loads` and `dumps` directly. See an example [here](https://cattrs.readthedocs.io/en/latest/preconf.html).
444
+ - Fix mappings with byte keys for the orjson, bson and tomlkit converters.
445
+ ([#241](https://github.com/python-attrs/cattrs/issues/241))
446
+
447
+ ## 1.10.0 (2022-01-04)
448
+
449
+ ```{note}
450
+ In this release, _cattrs_ introduces the {mod}`cattrs` package as the main entry point into the library, replacing the `cattr` package.
451
+
452
+ The `cattr` package is never going away, nor is it technically deprecated.
453
+ New functionality will be added only to the `cattrs` package, but there is no need to replace your current imports.
454
+
455
+ This change mirrors [a similar change in _attrs_](https://www.attrs.org/en/stable/names.html).
456
+ ```
457
+
458
+ - Add [PEP 563 (string annotations)](https://peps.python.org/pep-0563/) support for dataclasses.
459
+ ([#195](https://github.com/python-attrs/cattrs/issues/195))
460
+ - Fix handling of dictionaries with string Enum keys for bson, orjson, and tomlkit.
461
+ - Rename the {func}`cattrs.gen.make_dict_unstructure_fn` `omit_if_default` parameter to `_cattrs_omit_if_default`, for consistency. The `omit_if_default` parameters to {class}`GenConverter` and {func}`override` are unchanged.
462
+ - Following the changes in _attrs_ 21.3.0, add a {mod}`cattrs` package mirroring the existing `cattr` package. Both package names may be used as desired, and the `cattr` package isn't going away.
463
+
464
+ ## 1.9.0 (2021-12-06)
465
+
466
+ - Python 3.10 support, including support for the new union syntax (`A | B` vs `Union[A, B]`).
467
+ - The `GenConverter` can now properly structure generic classes with generic collection fields.
468
+ ([#149](https://github.com/python-attrs/cattrs/issues/149))
469
+ - `omit=True` now also affects generated structuring functions.
470
+ ([#166](https://github.com/python-attrs/cattrs/issues/166))
471
+ - `cattr.gen.{make_dict_structure_fn, make_dict_unstructure_fn}` now resolve type annotations automatically when PEP 563 is used.
472
+ ([#169](https://github.com/python-attrs/cattrs/issues/169))
473
+ - Protocols are now unstructured as their runtime types.
474
+ ([#177](https://github.com/python-attrs/cattrs/pull/177))
475
+ - Fix an issue generating structuring functions with renaming and `_cattrs_forbid_extra_keys=True`.
476
+ ([#190](https://github.com/python-attrs/cattrs/issues/190))
477
+
478
+ ## 1.8.0 (2021-08-13)
479
+
480
+ - Fix `GenConverter` mapping structuring for unannotated dicts on Python 3.8.
481
+ ([#151](https://github.com/python-attrs/cattrs/issues/151))
482
+ - The source code for generated un/structuring functions is stored in the `linecache` cache, which enables more informative stack traces when un/structuring errors happen using the `GenConverter`. This behavior can optionally be disabled to save memory.
483
+ - Support using the attr converter callback during structure.
484
+ By default, this is a method of last resort, but it can be elevated to the default by setting `prefer_attrib_converters=True` on `Converter` or `GenConverter`.
485
+ ([#138](https://github.com/python-attrs/cattrs/issues/138))
486
+ - Fix structuring recursive classes.
487
+ ([#159](https://github.com/python-attrs/cattrs/issues/159))
488
+ - Converters now support un/structuring hook factories. This is the most powerful and complex venue for customizing un/structuring. This had previously been an internal feature.
489
+ - The [Common Usage Examples](https://cattrs.readthedocs.io/en/latest/usage.html#using-factory-hooks) documentation page now has a section on advanced hook factory usage.
490
+ - `cattr.override` now supports the `omit` parameter, which makes _cattrs_ skip the atribute entirely when unstructuring.
491
+ - The `cattr.preconf.bson` module is now tested against the `bson` module bundled with the `pymongo` package, because that package is much more popular than the standalone PyPI `bson` package.
492
+
493
+ ## 1.7.1 (2021-05-28)
494
+
495
+ - `Literal` s are not supported on Python 3.9.0 (supported on 3.9.1 and later), so we skip importing them there.
496
+ ([#150](https://github.com/python-attrs/cattrs/issues/150))
497
+
498
+ ## 1.7.0 (2021-05-26)
499
+
500
+ - `cattr.global_converter` (which provides `cattr.unstructure`, `cattr.structure` etc.) is now an instance of `cattr.GenConverter`.
501
+ - `Literal` s are now supported and validated when structuring.
502
+ - Fix dependency metadata information for _attrs_.
503
+ ([#147](https://github.com/python-attrs/cattrs/issues/147))
504
+ - Fix `GenConverter` mapping structuring for unannotated dicts.
505
+ ([#148](https://github.com/python-attrs/cattrs/issues/148))
506
+
507
+ ## 1.6.0 (2021-04-28)
508
+
509
+ - _cattrs_ now uses Poetry.
510
+ - `GenConverter` mapping structuring is now ~25% faster, and unstructuring heterogenous tuples is significantly faster.
511
+ - Add `cattr.preconf`. This package contains modules for making converters for particular serialization libraries. We currently support the standard library `json`, and third-party `ujson`, `orjson`, `msgpack`, `bson`, `pyyaml` and `tomlkit` libraries.
512
+
513
+ ## 1.5.0 (2021-04-15)
514
+
515
+ - Fix an issue with `GenConverter` unstructuring _attrs_ classes and dataclasses with generic fields.
516
+ ([#65](https://github.com/python-attrs/cattrs/issues/65))
517
+ - `GenConverter` has support for easy overriding of collection unstructuring types (for example, unstructure all sets to lists) through its `unstruct_collection_overrides` argument.
518
+ ([#137](https://github.com/python-attrs/cattrs/pull/137))
519
+ - Unstructuring mappings with `GenConverter` is significantly faster.
520
+ - `GenConverter` supports strict handling of unexpected dictionary keys through its `forbid_extra_keys` argument.
521
+ ([#142](https://github.com/python-attrs/cattrs/pull/142))
522
+
523
+ ## 1.4.0 (2021-03-21)
524
+
525
+ - Fix an issue with `GenConverter` un/structuring hooks when a function hook is registered after the converter has already been used.
526
+ - Add support for `collections.abc.{Sequence, MutableSequence, Set, MutableSet}`. These should be used on 3.9+ instead of their `typing` alternatives, which are deprecated.
527
+ ([#128](https://github.com/python-attrs/cattrs/issues/128))
528
+ - The `GenConverter` will unstructure iterables (`list[T]`, `tuple[T, ...]`, `set[T]`) using their type argument instead of the runtime class if its elements, if possible. These unstructuring operations are up to 40% faster.
529
+ ([#129](https://github.com/python-attrs/cattrs/issues/129))
530
+ - Flesh out `Converter` and `GenConverter` initializer type annotations.
531
+ ([#131](https://github.com/python-attrs/cattrs/issues/131))
532
+ - Add support for `typing.Annotated` on Python 3.9+. _cattrs_ will use the first annotation present. _cattrs_ specific annotations may be added in the future.
533
+ ([#127](https://github.com/python-attrs/cattrs/issues/127))
534
+ - Add support for dataclasses.
535
+ ([#43](https://github.com/python-attrs/cattrs/issues/43))
536
+
537
+ ## 1.3.0 (2021-02-25)
538
+
539
+ - _cattrs_ now has a benchmark suite to help make and keep cattrs the fastest it can be. The instructions on using it can be found under the [Benchmarking](https://cattrs.readthedocs.io/en/latest/benchmarking.html) section in the docs.
540
+ ([#123](https://github.com/python-attrs/cattrs/pull/123))
541
+ - Fix an issue unstructuring tuples of non-primitives.
542
+ ([#125](https://github.com/python-attrs/cattrs/issues/125))
543
+ - _cattrs_ now calls `attr.resolve_types` on _attrs_ classes when registering un/structuring hooks.
544
+ - `GenConverter` structuring and unstructuring of _attrs_ classes is significantly faster.
545
+
546
+ ## 1.2.0 (2021-01-31)
547
+
548
+ - `converter.unstructure` now supports an optional parameter, `unstructure_as`, which can be used to unstructure something as a different type. Useful for unions.
549
+ - Improve support for union un/structuring hooks. Flesh out docs for advanced union handling.
550
+ ([#115](https://github.com/python-attrs/cattrs/pull/115))
551
+ - Fix `GenConverter` behavior with inheritance hierarchies of _attrs_ classes.
552
+ ([#117](https://github.com/python-attrs/cattrs/pull/117 [#116](https://github.com/python-attrs/cattrs/issues/116>))
553
+ - Refactor `GenConverter.un/structure_attrs_fromdict` into `GenConverter.gen_un/structure_attrs_fromdict` to allow calling back to `Converter.un/structure_attrs_fromdict` without sideeffects.
554
+ ([#118](https://github.com/python-attrs/cattrs/issues/118))
555
+
556
+ ## 1.1.2 (2020-11-29)
557
+
558
+ - The default disambiguator will not consider non-required fields any more.
559
+ ([#108](https://github.com/python-attrs/cattrs/pull/108))
560
+ - Fix a couple type annotations.
561
+ ([#107](https://github.com/python-attrs/cattrs/pull/107) [#105](https://github.com/python-attrs/cattrs/issues/105))
562
+ - Fix a `GenConverter` unstructuring issue and tests.
563
+
564
+ ## 1.1.1 (2020-10-30)
565
+
566
+ - Add metadata for supported Python versions.
567
+ ([#103](https://github.com/python-attrs/cattrs/pull/103))
568
+
569
+ ## 1.1.0 (2020-10-29)
570
+
571
+ - Python 2, 3.5 and 3.6 support removal. If you need it, use a version below 1.1.0.
572
+ - Python 3.9 support, including support for built-in generic types (`list[int]` vs `typing.List[int]`).
573
+ - _cattrs_ now includes functions to generate specialized structuring and unstructuring hooks. Specialized hooks are faster and support overrides (`omit_if_default` and `rename`). See the `cattr.gen` module.
574
+ - _cattrs_ now includes a converter variant, `cattr.GenConverter`, that automatically generates specialized hooks for attrs classes. This converter will become the default in the future.
575
+ - Generating specialized structuring hooks now invokes [attr.resolve_types](https://www.attrs.org/en/stable/api.html#attr.resolve_types) on a class if the class makes use of the new PEP 563 annotations.
576
+ - _cattrs_ now depends on _attrs_ >= 20.1.0, because of `attr.resolve_types`.
577
+ - Specialized hooks now support generic classes. The default converter will generate and use a specialized hook upon encountering a generic class.
578
+
579
+ ## 1.0.0 (2019-12-27)
580
+
581
+ - _attrs_ classes with private attributes can now be structured by default.
582
+ - Structuring from dictionaries is now more lenient: extra keys are ignored.
583
+ - _cattrs_ has improved type annotations for use with Mypy.
584
+ - Unstructuring sets and frozensets now works properly.
585
+
586
+ ## 0.9.1 (2019-10-26)
587
+
588
+ - Python 3.8 support.
589
+
590
+ ## 0.9.0 (2018-07-22)
591
+
592
+ - Python 3.7 support.
593
+
594
+ ## 0.8.1 (2018-06-19)
595
+
596
+ - The disambiguation function generator now supports unions of _attrs_ classes and NoneType.
597
+
598
+ ## 0.8.0 (2018-04-14)
599
+
600
+ - Distribution fix.
601
+
602
+ ## 0.7.0 (2018-04-12)
603
+
604
+ - Removed the undocumented `Converter.unstruct_strat` property setter.
605
+ - Removed the ability to set the `Converter.structure_attrs` instance field.
606
+ - Some micro-optimizations were applied; a `structure(unstructure(obj))` roundtrip
607
+ is now up to 2 times faster.
608
+
609
+ ## 0.6.0 (2017-12-25)
610
+
611
+ - Packaging fixes.
612
+ ([#17](https://github.com/python-attrs/cattrs/pull/17))
613
+
614
+ ## 0.5.0 (2017-12-11)
615
+
616
+ - structure/unstructure now supports using functions as well as classes for deciding the appropriate function.
617
+ - added `Converter.register_structure_hook_func`, to register a function instead of a class for determining handler func.
618
+ - added `Converter.register_unstructure_hook_func`, to register a function instead of a class for determining handler func.
619
+ - vendored typing is no longer needed, nor provided.
620
+ - Attributes with default values can now be structured if they are missing in the input.
621
+ ([#15](https://github.com/python-attrs/cattrs/pull/15))
622
+ - `Optional` attributes can no longer be structured if they are missing in the input.
623
+ - `cattr.typed` removed since the functionality is now present in _attrs_ itself.
624
+ Replace instances of `cattr.typed(type)` with `attr.ib(type=type)`.
625
+
626
+ ## 0.4.0 (2017-07-17)
627
+
628
+ - `Converter.loads` is now `Converter.structure`, and `Converter.dumps` is now `Converter.unstructure`.
629
+ - Python 2.7 is supported.
630
+ - Moved `cattr.typing` to `cattr.vendor.typing` to support different vendored versions of typing.py for Python 2 and Python 3.
631
+ - Type metadata can be added to _attrs_ classes using `cattr.typed`.
632
+
633
+ ## 0.3.0 (2017-03-18)
634
+
635
+ - Python 3.4 is no longer supported.
636
+ - Introduced `cattr.typing` for use with Python versions 3.5.2 and 3.6.0.
637
+ - Minor changes to work with newer versions of `typing`.
638
+ - Bare Optionals are not supported any more (use `Optional[Any]`).
639
+ - Attempting to load unrecognized classes will result in a ValueError, and a helpful message to register a loads hook.
640
+ - Loading _attrs_ classes is now documented.
641
+ - The global converter is now documented.
642
+ - `cattr.loads_attrs_fromtuple` and `cattr.loads_attrs_fromdict` are now exposed.
643
+
644
+ ## 0.2.0 (2016-10-02)
645
+
646
+ - Tests and documentation.
647
+
648
+ ## 0.1.0 (2016-08-13)
649
+
650
+ - First release on PyPI.
tasks/tasksmith-c756db832cf4/tests/source/Justfile ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python := ""
2
+ covcleanup := "true"
3
+
4
+ # Sync the environment, to a particular version if provided. The `python` variable takes precedence over the argument.
5
+ sync version="":
6
+ uv sync {{ if python != '' { '-p ' + python } else if version != '' { '-p ' + version } else { '' } }} --all-groups --all-extras
7
+
8
+ lint:
9
+ uv run -p python3.14 --group lint ruff check src/ tests bench
10
+ uv run -p python3.14 --group lint ruff format --check src tests docs/conf.py
11
+
12
+ test *args="-x --ff -n auto tests":
13
+ uv run {{ if python != '' { '-p ' + python } else { '' } }} --all-extras --group test --group lint pytest {{args}}
14
+
15
+ testall:
16
+ just python=python3.10 test
17
+ just python=pypy3.10 test
18
+ just python=python3.11 test
19
+ just python=python3.12 test
20
+ just python=python3.13 test
21
+ just python=python3.14 test
22
+
23
+ cov *args="-x --ff -n auto tests":
24
+ uv run {{ if python != '' { '-p ' + python } else { '' } }} --all-extras --group test --group lint coverage run -m pytest {{args}}
25
+ {{ if covcleanup == "true" { "uv run coverage combine" } else { "" } }}
26
+ {{ if covcleanup == "true" { "uv run coverage report" } else { "" } }}
27
+ {{ if covcleanup == "true" { "@rm .coverage*" } else { "" } }}
28
+
29
+ covall:
30
+ just python=python3.10 covcleanup=false cov
31
+ just python=pypy3.10 covcleanup=false cov
32
+ just python=python3.11 covcleanup=false cov
33
+ just python=python3.12 covcleanup=false cov
34
+ just python=python3.13 covcleanup=false cov
35
+ just python=python3.14 covcleanup=false cov
36
+ uv run coverage combine
37
+ uv run coverage report
38
+ @rm .coverage*
39
+
40
+ bench-cmp:
41
+ uv run --group test pytest bench --benchmark-compare
42
+
43
+ bench:
44
+ uv run --group test pytest bench --benchmark-save base
45
+
46
+ docs output_dir="_build": ## generate Sphinx HTML documentation, including API docs
47
+ make -C docs -e BUILDDIR={{output_dir}} clean
48
+ make -C docs -e BUILDDIR={{output_dir}} doctest
49
+ make -C docs -e BUILDDIR={{output_dir}} html
50
+
51
+ htmllive: docs ## compile the docs watching for changes
52
+ make -C docs htmllive
tasks/tasksmith-c756db832cf4/tests/source/LICENSE ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ MIT License
3
+
4
+ Copyright (c) 2016, Tin Tvrtković
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
+
8
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11
+
tasks/tasksmith-c756db832cf4/tests/source/MANIFEST.in ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ include AUTHORS.rst
2
+ include CONTRIBUTING.rst
3
+ include HISTORY.rst
4
+ include LICENSE
5
+ include README.rst
6
+ include src/cattr/py.typed
7
+
8
+ recursive-exclude * __pycache__
9
+ recursive-exclude * *.py[co]
10
+
11
+ recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif
tasks/tasksmith-c756db832cf4/tests/source/README.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # *cattrs*: Flexible Object Serialization and Validation
2
+
3
+ *Because validation belongs to the edges.*
4
+
5
+ [![Documentation](https://img.shields.io/badge/Docs-Read%20The%20Docs-black)](https://catt.rs/)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-C06524)](https://github.com/hynek/stamina/blob/main/LICENSE)
7
+ [![PyPI](https://img.shields.io/pypi/v/cattrs.svg)](https://pypi.python.org/pypi/cattrs)
8
+ [![Supported Python Versions](https://img.shields.io/pypi/pyversions/cattrs.svg)](https://github.com/python-attrs/cattrs)
9
+ [![Downloads](https://static.pepy.tech/badge/cattrs/month)](https://pepy.tech/project/cattrs)
10
+ [![Coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/Tinche/22405310d6a663164d894a2beab4d44d/raw/covbadge.json)](https://github.com/python-attrs/cattrs/actions/workflows/main.yml)
11
+
12
+ ---
13
+
14
+ <!-- begin-teaser -->
15
+
16
+ **cattrs** is a Swiss Army knife for (un)structuring and validating data in Python.
17
+ In practice, that means it converts **unstructured dictionaries** into **proper classes** and back, while **validating** their contents.
18
+
19
+ <!-- end-teaser -->
20
+
21
+
22
+ ## Example
23
+
24
+ <!-- begin-example -->
25
+
26
+ _cattrs_ works best with [_attrs_](https://www.attrs.org/) classes, and [dataclasses](https://docs.python.org/3/library/dataclasses.html) where simple (un-)structuring works out of the box, even for nested data, without polluting your data model with serialization details:
27
+
28
+ ```python
29
+ >>> from attrs import define
30
+ >>> from cattrs import structure, unstructure
31
+ >>> @define
32
+ ... class C:
33
+ ... a: int
34
+ ... b: list[str]
35
+ >>> instance = structure({'a': 1, 'b': ['x', 'y']}, C)
36
+ >>> instance
37
+ C(a=1, b=['x', 'y'])
38
+ >>> unstructure(instance)
39
+ {'a': 1, 'b': ['x', 'y']}
40
+ ```
41
+
42
+ <!-- end-teaser -->
43
+ <!-- end-example -->
44
+
45
+ Have a look at [*Why *cattrs*?*](https://catt.rs/en/latest/why.html) for more examples!
46
+
47
+ <!-- begin-why -->
48
+
49
+ ## Features
50
+
51
+ ### Recursive Unstructuring
52
+
53
+ - _attrs_ classes and dataclasses are converted into dictionaries in a way similar to `attrs.asdict()`, or into tuples in a way similar to `attrs.astuple()`.
54
+ - Enumeration instances are converted to their values.
55
+ - Other types are let through without conversion. This includes types such as integers, dictionaries, lists and instances of non-_attrs_ classes.
56
+ - Custom converters for any type can be registered using `register_unstructure_hook`.
57
+
58
+
59
+ ### Recursive Structuring
60
+
61
+ Converts unstructured data into structured data, recursively, according to your specification given as a type.
62
+ The following types are supported:
63
+
64
+ - `typing.Optional[T]` and its 3.10+ form, `T | None`.
65
+ - `list[T]`, `typing.List[T]`, `typing.MutableSequence[T]`, `typing.Sequence[T]` convert to lists.
66
+ - `tuple` and `typing.Tuple` (both variants, `tuple[T, ...]` and `tuple[X, Y, Z]`).
67
+ - `set[T]`, `typing.MutableSet[T]`, and `typing.Set[T]` convert to sets.
68
+ - `frozenset[T]`, and `typing.FrozenSet[T]` convert to frozensets.
69
+ - `dict[K, V]`, `typing.Dict[K, V]`, `typing.MutableMapping[K, V]`, and `typing.Mapping[K, V]` convert to dictionaries.
70
+ - [`typing.TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict), both ordinary and generic.
71
+ - [`typing.NewType`](https://docs.python.org/3/library/typing.html#newtype)
72
+ - [PEP 695 type aliases](https://docs.python.org/3/library/typing.html#type-aliases) on 3.12+
73
+ - _attrs_ classes with simple attributes and the usual `__init__`[^simple].
74
+ - All _attrs_ classes and dataclasses with the usual `__init__`, if their complex attributes have type metadata.
75
+ - Unions of supported _attrs_ classes, given that all of the classes have a unique field.
76
+ - Unions of anything, if you provide a disambiguation function for it.
77
+ - Custom converters for any type can be registered using `register_structure_hook`.
78
+
79
+ [^simple]: Simple attributes are attributes that can be assigned unstructured data, like numbers, strings, and collections of unstructured data.
80
+
81
+
82
+ ### Batteries Included
83
+
84
+ _cattrs_ comes with pre-configured converters for a number of serialization libraries, including JSON (standard library, [_orjson_](https://pypi.org/project/orjson/), [UltraJSON](https://pypi.org/project/ujson/)), [_msgpack_](https://pypi.org/project/msgpack/), [_cbor2_](https://pypi.org/project/cbor2/), [_bson_](https://pypi.org/project/bson/), [PyYAML](https://pypi.org/project/PyYAML/), [_tomlkit_](https://pypi.org/project/tomlkit/) and [_msgspec_](https://pypi.org/project/msgspec/) (supports only JSON at this time).
85
+
86
+ For details, see the [cattrs.preconf package](https://catt.rs/en/stable/preconf.html).
87
+
88
+
89
+ ## Design Decisions
90
+
91
+ _cattrs_ is based on a few fundamental design decisions:
92
+
93
+ - Un/structuring rules are separate from the models.
94
+ This allows models to have a one-to-many relationship with un/structuring rules, and to create un/structuring rules for models which you do not own and you cannot change.
95
+ (_cattrs_ can be configured to use un/structuring rules from models using the [`use_class_methods` strategy](https://catt.rs/en/latest/strategies.html#using-class-specific-structure-and-unstructure-methods).)
96
+ - Invent as little as possible; reuse existing ordinary Python instead.
97
+ For example, _cattrs_ did not have a custom exception type to group exceptions until the sanctioned Python [`exceptiongroups`](https://docs.python.org/3/library/exceptions.html#ExceptionGroup).
98
+ A side-effect of this design decision is that, in a lot of cases, when you're solving _cattrs_ problems you're actually learning Python instead of learning _cattrs_.
99
+ - Resist the temptation to guess.
100
+ If there are two ways of solving a problem, _cattrs_ should refuse to guess and let the user configure it themselves.
101
+
102
+ A foolish consistency is the hobgoblin of little minds, so these decisions can and are sometimes broken, but they have proven to be a good foundation.
103
+
104
+
105
+ <!-- end-why -->
106
+
107
+ ## Credits
108
+
109
+ Major credits to Hynek Schlawack for creating [attrs](https://attrs.org) and its predecessor, [characteristic](https://github.com/hynek/characteristic).
110
+
111
+ _cattrs_ is tested with [Hypothesis](http://hypothesis.readthedocs.io/en/latest/), by David R. MacIver.
112
+
113
+ _cattrs_ is benchmarked using [perf](https://github.com/haypo/perf) and [pytest-benchmark](https://pytest-benchmark.readthedocs.io/en/latest/index.html).
114
+
115
+ This package was created with [Cookiecutter](https://github.com/audreyr/cookiecutter) and the [`audreyr/cookiecutter-pypackage`](https://github.com/audreyr/cookiecutter-pypackage) project template.
tasks/tasksmith-c756db832cf4/tests/source/bench/__init__.py ADDED
File without changes
tasks/tasksmith-c756db832cf4/tests/source/bench/test_attrs_collections.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import IntEnum
2
+ from typing import Mapping, MutableMapping
3
+
4
+ import pytest
5
+ from attrs import define, frozen
6
+
7
+ from cattrs import BaseConverter, Converter, UnstructureStrategy
8
+
9
+
10
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
11
+ @pytest.mark.parametrize(
12
+ "unstructure_strat", [UnstructureStrategy.AS_DICT, UnstructureStrategy.AS_TUPLE]
13
+ )
14
+ def test_unstructure_attrs_lists(benchmark, converter_cls, unstructure_strat):
15
+ """
16
+ Benchmark a large (30 attributes) attrs class containing lists of
17
+ primitives.
18
+ """
19
+
20
+ class E(IntEnum):
21
+ ONE = 1
22
+ TWO = 2
23
+
24
+ @define
25
+ class C:
26
+ a: list[int]
27
+ b: list[float]
28
+ c: list[str]
29
+ d: list[bytes]
30
+ e: list[E]
31
+ f: list[int]
32
+ g: list[float]
33
+ h: list[str]
34
+ i: list[bytes]
35
+ j: list[E]
36
+ k: list[int]
37
+ l: list[float] # noqa: E741
38
+ m: list[str]
39
+ n: list[bytes]
40
+ o: list[E]
41
+ p: list[int]
42
+ q: list[float]
43
+ r: list[str]
44
+ s: list[bytes]
45
+ t: list[E]
46
+ u: list[int]
47
+ v: list[float]
48
+ w: list[str]
49
+ x: list[bytes]
50
+ y: list[E]
51
+ z: list[int]
52
+ aa: list[float]
53
+ ab: list[str]
54
+ ac: list[bytes]
55
+ ad: list[E]
56
+
57
+ c = converter_cls(unstruct_strat=unstructure_strat)
58
+
59
+ benchmark(
60
+ c.unstructure,
61
+ C(
62
+ [1] * 3,
63
+ [1.0] * 3,
64
+ ["a small string"] * 3,
65
+ [b"test"] * 3,
66
+ [E.ONE] * 3,
67
+ [2] * 3,
68
+ [2.0] * 3,
69
+ ["a small string"] * 3,
70
+ [b"test"] * 3,
71
+ [E.TWO] * 3,
72
+ [3] * 3,
73
+ [3.0] * 3,
74
+ ["a small string"] * 3,
75
+ [b"test"] * 3,
76
+ [E.ONE] * 3,
77
+ [4] * 3,
78
+ [4.0] * 3,
79
+ ["a small string"] * 3,
80
+ [b"test"] * 3,
81
+ [E.TWO] * 3,
82
+ [5] * 3,
83
+ [5.0] * 3,
84
+ ["a small string"] * 3,
85
+ [b"test"] * 3,
86
+ [E.ONE] * 3,
87
+ [6] * 3,
88
+ [6.0] * 3,
89
+ ["a small string"] * 3,
90
+ [b"test"] * 3,
91
+ [E.TWO] * 3,
92
+ ),
93
+ )
94
+
95
+
96
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
97
+ @pytest.mark.parametrize(
98
+ "unstructure_strat", [UnstructureStrategy.AS_DICT, UnstructureStrategy.AS_TUPLE]
99
+ )
100
+ def test_unstructure_attrs_mappings(benchmark, converter_cls, unstructure_strat):
101
+ """
102
+ Benchmark an attrs class containing mappings.
103
+ """
104
+
105
+ @frozen
106
+ class FrozenCls:
107
+ a: int
108
+
109
+ @define
110
+ class C:
111
+ a: Mapping[int, str]
112
+ b: dict[float, bytes]
113
+ c: MutableMapping[int, FrozenCls]
114
+
115
+ c = converter_cls(unstruct_strat=unstructure_strat)
116
+
117
+ benchmark(
118
+ c.unstructure,
119
+ C(
120
+ {i: str(i) for i in range(30)},
121
+ {float(i): bytes(i) for i in range(30)},
122
+ {i: FrozenCls(i) for i in range(30)},
123
+ ),
124
+ )
125
+
126
+
127
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
128
+ def test_structure_attrs_mappings(benchmark, converter_cls):
129
+ """
130
+ Benchmark an attrs class containing mappings.
131
+ """
132
+
133
+ @frozen
134
+ class FrozenCls:
135
+ a: int
136
+
137
+ @define
138
+ class C:
139
+ a: Mapping[int, str]
140
+ b: dict[float, bytes]
141
+ c: MutableMapping[int, FrozenCls]
142
+
143
+ c = converter_cls()
144
+
145
+ inst = C(
146
+ {i: str(i) for i in range(30)},
147
+ {float(i): bytes(i) for i in range(30)},
148
+ {i: FrozenCls(i) for i in range(30)},
149
+ )
150
+ raw = c.unstructure(inst)
151
+
152
+ benchmark(c.structure, raw, C)
tasks/tasksmith-c756db832cf4/tests/source/bench/test_attrs_nested.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Benchmark attrs containing other attrs classes."""
2
+
3
+ import pytest
4
+ from attrs import define
5
+
6
+ from cattrs import BaseConverter, Converter, UnstructureStrategy
7
+
8
+
9
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
10
+ @pytest.mark.parametrize(
11
+ "unstructure_strat", [UnstructureStrategy.AS_DICT, UnstructureStrategy.AS_TUPLE]
12
+ )
13
+ def test_unstructure_attrs_nested(benchmark, converter_cls, unstructure_strat):
14
+ c = converter_cls(unstruct_strat=unstructure_strat)
15
+
16
+ @define
17
+ class InnerA:
18
+ a: int
19
+ b: float
20
+ c: str
21
+ d: bytes
22
+
23
+ @define
24
+ class InnerB:
25
+ a: int
26
+ b: float
27
+ c: str
28
+ d: bytes
29
+
30
+ @define
31
+ class InnerC:
32
+ a: int
33
+ b: float
34
+ c: str
35
+ d: bytes
36
+
37
+ @define
38
+ class InnerD:
39
+ a: int
40
+ b: float
41
+ c: str
42
+ d: bytes
43
+
44
+ @define
45
+ class InnerE:
46
+ a: int
47
+ b: float
48
+ c: str
49
+ d: bytes
50
+
51
+ @define
52
+ class Outer:
53
+ a: InnerA
54
+ b: InnerB
55
+ c: InnerC
56
+ d: InnerD
57
+ e: InnerE
58
+
59
+ inst = Outer(
60
+ InnerA(1, 1.0, "one", b"one"),
61
+ InnerB(2, 2.0, "two", b"two"),
62
+ InnerC(3, 3.0, "three", b"three"),
63
+ InnerD(4, 4.0, "four", b"four"),
64
+ InnerE(5, 5.0, "five", b"five"),
65
+ )
66
+
67
+ benchmark(c.unstructure, inst)
68
+
69
+
70
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
71
+ @pytest.mark.parametrize(
72
+ "unstructure_strat", [UnstructureStrategy.AS_DICT, UnstructureStrategy.AS_TUPLE]
73
+ )
74
+ def test_unstruct_attrs_deep_nest(benchmark, converter_cls, unstructure_strat):
75
+ c = converter_cls(unstruct_strat=unstructure_strat)
76
+
77
+ @define
78
+ class InnerA:
79
+ a: int
80
+ b: float
81
+ c: str
82
+ d: bytes
83
+
84
+ @define
85
+ class InnerB:
86
+ a: InnerA
87
+ b: InnerA
88
+ c: InnerA
89
+ d: InnerA
90
+
91
+ @define
92
+ class InnerC:
93
+ a: InnerB
94
+ b: InnerB
95
+ c: InnerB
96
+ d: InnerB
97
+
98
+ @define
99
+ class InnerD:
100
+ a: InnerC
101
+ b: InnerC
102
+ c: InnerC
103
+ d: InnerC
104
+
105
+ @define
106
+ class InnerE:
107
+ a: InnerD
108
+ b: InnerD
109
+ c: InnerD
110
+ d: InnerD
111
+
112
+ @define
113
+ class Outer:
114
+ a: InnerE
115
+ b: InnerE
116
+ c: InnerE
117
+ d: InnerE
118
+
119
+ def make_inner_a():
120
+ return InnerA(1, 1.0, "one", b"one")
121
+
122
+ def make_inner_b():
123
+ return InnerB(*[make_inner_a() for _ in range(4)])
124
+
125
+ def make_inner_c():
126
+ return InnerC(*[make_inner_b() for _ in range(4)])
127
+
128
+ def make_inner_d():
129
+ return InnerD(*[make_inner_c() for _ in range(4)])
130
+
131
+ def make_inner_e():
132
+ return InnerE(*[make_inner_d() for _ in range(4)])
133
+
134
+ inst = Outer(*[make_inner_e() for _ in range(4)])
135
+
136
+ benchmark(c.unstructure, inst)
tasks/tasksmith-c756db832cf4/tests/source/bench/test_attrs_primitives.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import IntEnum
2
+
3
+ import pytest
4
+ from attrs import define
5
+
6
+ from cattrs import BaseConverter, Converter, UnstructureStrategy
7
+
8
+
9
+ class E(IntEnum):
10
+ ONE = 1
11
+ TWO = 2
12
+
13
+
14
+ @define
15
+ class C:
16
+ a: int
17
+ b: float
18
+ c: str
19
+ d: bytes
20
+ e: E
21
+ f: int
22
+ g: float
23
+ h: str
24
+ i: bytes
25
+ j: E
26
+ k: int
27
+ l: float # noqa: E741
28
+ m: str
29
+ n: bytes
30
+ o: E
31
+ p: int
32
+ q: float
33
+ r: str
34
+ s: bytes
35
+ t: E
36
+ u: int
37
+ v: float
38
+ w: str
39
+ x: bytes
40
+ y: E
41
+ z: int
42
+ aa: float
43
+ ab: str
44
+ ac: bytes
45
+ ad: E
46
+
47
+
48
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
49
+ @pytest.mark.parametrize(
50
+ "unstructure_strat", [UnstructureStrategy.AS_DICT, UnstructureStrategy.AS_TUPLE]
51
+ )
52
+ def test_unstructure_attrs_primitives(benchmark, converter_cls, unstructure_strat):
53
+ """Benchmark a large (30 attributes) attrs class containing primitives."""
54
+
55
+ c = converter_cls(unstruct_strat=unstructure_strat)
56
+
57
+ benchmark(
58
+ c.unstructure,
59
+ C(
60
+ 1,
61
+ 1.0,
62
+ "a small string",
63
+ b"test",
64
+ E.ONE,
65
+ 2,
66
+ 2.0,
67
+ "a small string",
68
+ b"test",
69
+ E.TWO,
70
+ 3,
71
+ 3.0,
72
+ "a small string",
73
+ b"test",
74
+ E.ONE,
75
+ 4,
76
+ 4.0,
77
+ "a small string",
78
+ b"test",
79
+ E.TWO,
80
+ 5,
81
+ 5.0,
82
+ "a small string",
83
+ b"test",
84
+ E.ONE,
85
+ 6,
86
+ 6.0,
87
+ "a small string",
88
+ b"test",
89
+ E.TWO,
90
+ ),
91
+ )
92
+
93
+
94
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
95
+ @pytest.mark.parametrize(
96
+ "unstructure_strat", [UnstructureStrategy.AS_DICT, UnstructureStrategy.AS_TUPLE]
97
+ )
98
+ def test_structure_attrs_primitives(benchmark, converter_cls, unstructure_strat):
99
+ """Benchmark a large (30 attributes) attrs class containing primitives."""
100
+
101
+ c = converter_cls(unstruct_strat=unstructure_strat)
102
+
103
+ inst = C(
104
+ 1,
105
+ 1.0,
106
+ "a small string",
107
+ b"test",
108
+ E.ONE,
109
+ 2,
110
+ 2.0,
111
+ "a small string",
112
+ b"test",
113
+ E.TWO,
114
+ 3,
115
+ 3.0,
116
+ "a small string",
117
+ b"test",
118
+ E.ONE,
119
+ 4,
120
+ 4.0,
121
+ "a small string",
122
+ b"test",
123
+ E.TWO,
124
+ 5,
125
+ 5.0,
126
+ "a small string",
127
+ b"test",
128
+ E.ONE,
129
+ 6,
130
+ 6.0,
131
+ "a small string",
132
+ b"test",
133
+ E.TWO,
134
+ )
135
+
136
+ raw = c.unstructure(inst)
137
+
138
+ benchmark(c.structure, raw, C)
tasks/tasksmith-c756db832cf4/tests/source/bench/test_enums.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum, IntEnum, StrEnum
2
+
3
+ import pytest
4
+
5
+ from cattrs import BaseConverter, Converter
6
+ from cattrs.preconf.msgspec import MsgspecJsonConverter
7
+ from cattrs.preconf.orjson import OrjsonConverter
8
+
9
+
10
+ class SimpleEnum(Enum):
11
+ FIRST = "first"
12
+ SECOND = "second"
13
+ THIRD = "third"
14
+
15
+
16
+ class SimpleIntEnum(IntEnum):
17
+ ONE = 1
18
+ TWO = 2
19
+ THREE = 3
20
+
21
+
22
+ class SimpleStrEnum(StrEnum):
23
+ ALPHA = "alpha"
24
+ BETA = "beta"
25
+ GAMMA = "gamma"
26
+
27
+
28
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter, MsgspecJsonConverter, OrjsonConverter])
29
+ def test_unstructure_simple_enum(benchmark, converter_cls):
30
+ """Benchmark unstructuring a simple enum."""
31
+ c = converter_cls()
32
+ benchmark(c.unstructure, SimpleEnum.FIRST)
33
+
34
+
35
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter, MsgspecJsonConverter, OrjsonConverter])
36
+ def test_structure_simple_enum(benchmark, converter_cls):
37
+ """Benchmark structuring a simple enum."""
38
+ c = converter_cls()
39
+ benchmark(c.structure, "first", SimpleEnum)
40
+
41
+
42
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter, MsgspecJsonConverter, OrjsonConverter])
43
+ def test_unstructure_simple_int_enum(benchmark, converter_cls):
44
+ """Benchmark unstructuring a simple IntEnum."""
45
+ c = converter_cls()
46
+ benchmark(c.unstructure, SimpleIntEnum.ONE)
47
+
48
+
49
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter, MsgspecJsonConverter, OrjsonConverter])
50
+ def test_structure_simple_int_enum(benchmark, converter_cls):
51
+ """Benchmark structuring a simple IntEnum."""
52
+ c = converter_cls()
53
+ benchmark(c.structure, 1, SimpleIntEnum)
54
+
55
+
56
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter, MsgspecJsonConverter, OrjsonConverter])
57
+ def test_unstructure_simple_str_enum(benchmark, converter_cls):
58
+ """Benchmark unstructuring a simple StrEnum."""
59
+ c = converter_cls()
60
+ benchmark(c.unstructure, SimpleStrEnum.ALPHA)
61
+
62
+
63
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter, MsgspecJsonConverter, OrjsonConverter])
64
+ def test_structure_simple_str_enum(benchmark, converter_cls):
65
+ """Benchmark structuring a simple StrEnum."""
66
+ c = converter_cls()
67
+ benchmark(c.structure, "alpha", SimpleStrEnum)
68
+
tasks/tasksmith-c756db832cf4/tests/source/bench/test_primitives.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from cattrs import BaseConverter, Converter
4
+
5
+
6
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
7
+ def test_unstructure_int(benchmark, converter_cls):
8
+ c = converter_cls()
9
+
10
+ benchmark(c.unstructure, 5)
11
+
12
+
13
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
14
+ def test_unstructure_float(benchmark, converter_cls):
15
+ c = converter_cls()
16
+
17
+ benchmark(c.unstructure, 15.0)
tasks/tasksmith-c756db832cf4/tests/source/bench/test_tuples.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from cattrs import BaseConverter, Converter
4
+
5
+ HETERO_TUPLE = tuple[int, str, float, int, str, float]
6
+ HETERO_RAW = [1.0, 2, "3", 4.0, 5, "6"]
7
+ HETERO_VALUE = (1, "2", 3.0, 4, "5", 6.0)
8
+ HOMO_TUPLE = tuple[int, ...]
9
+ HOMO_RAW = ["1", 2, 3.0, 4, 5.0, "6"]
10
+
11
+
12
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
13
+ @pytest.mark.parametrize("detailed_validation", [True, False])
14
+ def test_structure_hetero_tuple(benchmark, converter_cls, detailed_validation):
15
+ """Benchmark steady-state heterogeneous tuple structuring."""
16
+ c = converter_cls(detailed_validation=detailed_validation)
17
+
18
+ benchmark(c.structure, HETERO_RAW, HETERO_TUPLE)
19
+
20
+
21
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
22
+ def test_unstructure_hetero_tuple(benchmark, converter_cls):
23
+ """Benchmark heterogeneous tuple unstructuring."""
24
+ c = converter_cls()
25
+
26
+ benchmark(c.unstructure, HETERO_VALUE, HETERO_TUPLE)
27
+
28
+
29
+ @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
30
+ @pytest.mark.parametrize("detailed_validation", [True, False])
31
+ def test_structure_homo_tuple(benchmark, converter_cls, detailed_validation):
32
+ """Benchmark homogeneous tuple structuring."""
33
+ c = converter_cls(detailed_validation=detailed_validation)
34
+
35
+ benchmark(c.structure, HOMO_RAW, HOMO_TUPLE)
tasks/tasksmith-c756db832cf4/tests/source/docs/Makefile ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Makefile for Sphinx documentation
2
+ #
3
+
4
+ # You can set these variables from the command line.
5
+ SPHINXOPTS =
6
+ SPHINXBUILD = uv run --all-extras --group docs sphinx-build
7
+ PAPER =
8
+ BUILDDIR = _build
9
+
10
+ # Internal variables.
11
+ PAPEROPT_a4 = -D latex_paper_size=a4
12
+ PAPEROPT_letter = -D latex_paper_size=letter
13
+ ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
14
+ # the i18n builder cannot share the environment and doctrees with the others
15
+ I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
16
+
17
+ .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18
+
19
+ help:
20
+ @echo "Please use \`make <target>' where <target> is one of"
21
+ @echo " html to make standalone HTML files"
22
+ @echo " dirhtml to make HTML files named index.html in directories"
23
+ @echo " singlehtml to make a single large HTML file"
24
+ @echo " pickle to make pickle files"
25
+ @echo " json to make JSON files"
26
+ @echo " htmlhelp to make HTML files and a HTML help project"
27
+ @echo " qthelp to make HTML files and a qthelp project"
28
+ @echo " devhelp to make HTML files and a Devhelp project"
29
+ @echo " epub to make an epub"
30
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
31
+ @echo " latexpdf to make LaTeX files and run them through pdflatex"
32
+ @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
33
+ @echo " text to make text files"
34
+ @echo " man to make manual pages"
35
+ @echo " texinfo to make Texinfo files"
36
+ @echo " info to make Texinfo files and run them through makeinfo"
37
+ @echo " gettext to make PO message catalogs"
38
+ @echo " changes to make an overview of all changed/added/deprecated items"
39
+ @echo " xml to make Docutils-native XML files"
40
+ @echo " pseudoxml to make pseudoxml-XML files for display purposes"
41
+ @echo " linkcheck to check all external links for integrity"
42
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
43
+
44
+ clean:
45
+ rm -rf $(BUILDDIR)/*
46
+
47
+ html:
48
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
49
+ @echo
50
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
51
+
52
+ dirhtml:
53
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
54
+ @echo
55
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
56
+
57
+ singlehtml:
58
+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
59
+ @echo
60
+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
61
+
62
+ pickle:
63
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
64
+ @echo
65
+ @echo "Build finished; now you can process the pickle files."
66
+
67
+ json:
68
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
69
+ @echo
70
+ @echo "Build finished; now you can process the JSON files."
71
+
72
+ htmlhelp:
73
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
74
+ @echo
75
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
76
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
77
+
78
+ qthelp:
79
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
80
+ @echo
81
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
82
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
83
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/cattrs.qhcp"
84
+ @echo "To view the help file:"
85
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/cattrs.qhc"
86
+
87
+ devhelp:
88
+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
89
+ @echo
90
+ @echo "Build finished."
91
+ @echo "To view the help file:"
92
+ @echo "# mkdir -p $$HOME/.local/share/devhelp/cattrs"
93
+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/cattrs"
94
+ @echo "# devhelp"
95
+
96
+ epub:
97
+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
98
+ @echo
99
+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
100
+
101
+ latex:
102
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
103
+ @echo
104
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
105
+ @echo "Run \`make' in that directory to run these through (pdf)latex" \
106
+ "(use \`make latexpdf' here to do that automatically)."
107
+
108
+ latexpdf:
109
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
110
+ @echo "Running LaTeX files through pdflatex..."
111
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf
112
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
113
+
114
+ latexpdfja:
115
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
116
+ @echo "Running LaTeX files through platex and dvipdfmx..."
117
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
118
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
119
+
120
+ text:
121
+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
122
+ @echo
123
+ @echo "Build finished. The text files are in $(BUILDDIR)/text."
124
+
125
+ man:
126
+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
127
+ @echo
128
+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
129
+
130
+ texinfo:
131
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
132
+ @echo
133
+ @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
134
+ @echo "Run \`make' in that directory to run these through makeinfo" \
135
+ "(use \`make info' here to do that automatically)."
136
+
137
+ info:
138
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
139
+ @echo "Running Texinfo files through makeinfo..."
140
+ make -C $(BUILDDIR)/texinfo info
141
+ @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
142
+
143
+ gettext:
144
+ $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
145
+ @echo
146
+ @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
147
+
148
+ changes:
149
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
150
+ @echo
151
+ @echo "The overview file is in $(BUILDDIR)/changes."
152
+
153
+ linkcheck:
154
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
155
+ @echo
156
+ @echo "Link check complete; look for any errors in the above output " \
157
+ "or in $(BUILDDIR)/linkcheck/output.txt."
158
+
159
+ doctest:
160
+ PYTHONHASHSEED=0 $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
161
+ @echo "Testing of doctests in the sources finished, look at the " \
162
+ "results in $(BUILDDIR)/doctest/output.txt."
163
+
164
+ xml:
165
+ $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
166
+ @echo
167
+ @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
168
+
169
+ pseudoxml:
170
+ $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
171
+ @echo
172
+ @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
173
+
174
+ .PHONY: apidoc
175
+ apidoc:
176
+ uv run sphinx-apidoc -o . ../src/cattrs/ '../**/converters.py' -f -M
177
+
178
+ ## htmlview to open the index page built by the html target in your browser
179
+ .PHONY: htmlview
180
+ htmlview: html
181
+ uv run python -c "import os, webbrowser; webbrowser.open('file://' + os.path.realpath('$(BUILDDIR)/html/index.html'))"
182
+
183
+ ## htmllive to rebuild and reload HTML files in your browser
184
+ .PHONY: htmllive
185
+ htmllive: SPHINXBUILD = uv run sphinx-autobuild
186
+ htmllive: SPHINXERRORHANDLING = --re-ignore="/\.idea/|/venv/|/pep-0000.rst|/topic/"
187
+ htmllive: html
tasks/tasksmith-c756db832cf4/tests/source/docs/_static/custom.css ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import url('https://rsms.me/inter/inter.css');
2
+
3
+ :root {
4
+ font-feature-settings: 'liga' 1, 'calt' 1; /* fix for Chrome */
5
+ }
6
+
7
+ @supports (font-variation-settings: normal) {
8
+ :root { font-family: InterVariable, sans-serif; }
9
+ }
10
+
11
+ /* ubuntu-mono-regular - latin */
12
+ @font-face {
13
+ font-family: "Ubuntu Mono";
14
+ font-style: normal;
15
+ font-weight: 400;
16
+ src: local(""),
17
+ url("./fonts/ubuntu-mono-v15-latin-regular.woff2") format("woff2"),
18
+ /* Chrome 26+, Opera 23+, Firefox 39+ */
19
+ url("./fonts/ubuntu-mono-v15-latin-regular.woff") format("woff"); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
20
+ }
21
+
22
+ /* ubuntu-mono-italic - latin */
23
+ @font-face {
24
+ font-family: "Ubuntu Mono";
25
+ font-style: italic;
26
+ font-weight: 400;
27
+ src: local(""),
28
+ url("./fonts/ubuntu-mono-v15-latin-italic.woff2") format("woff2"),
29
+ /* Chrome 26+, Opera 23+, Firefox 39+ */
30
+ url("./fonts/ubuntu-mono-v15-latin-italic.woff") format("woff"); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
31
+ }
32
+
33
+ /* ubuntu-mono-700 - latin */
34
+ @font-face {
35
+ font-family: "Ubuntu Mono";
36
+ font-style: normal;
37
+ font-weight: 700;
38
+ src: local(""), url("./fonts/ubuntu-mono-v15-latin-700.woff2") format("woff2"),
39
+ /* Chrome 26+, Opera 23+, Firefox 39+ */
40
+ url("./fonts/ubuntu-mono-v15-latin-700.woff") format("woff"); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
41
+ }
42
+
43
+ /* ubuntu-mono-700italic - latin */
44
+ @font-face {
45
+ font-family: "Ubuntu Mono";
46
+ font-style: italic;
47
+ font-weight: 700;
48
+ src: local(""),
49
+ url("./fonts/ubuntu-mono-v15-latin-700italic.woff2") format("woff2"),
50
+ /* Chrome 26+, Opera 23+, Firefox 39+ */
51
+ url("./fonts/ubuntu-mono-v15-latin-700italic.woff") format("woff"); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
52
+ }
53
+
54
+ h2,
55
+ h3 {
56
+ margin-bottom: 0.5em;
57
+ margin-top: 2rem;
58
+ }
59
+
60
+ :target > h1:first-of-type,
61
+ :target > h2:first-of-type,
62
+ :target > h3:first-of-type,
63
+ span:target ~ h1:first-of-type,
64
+ span:target ~ h2:first-of-type,
65
+ span:target ~ h3:first-of-type,
66
+ span:target ~ h4:first-of-type,
67
+ span:target ~ h5:first-of-type,
68
+ span:target ~ h6:first-of-type {
69
+ text-decoration: underline dashed;
70
+ text-decoration-thickness: 1px;
71
+ }
72
+
73
+ div.article-container > article {
74
+ font-size: 17px;
75
+ line-height: 29px;
76
+ }
77
+
78
+ div.admonition {
79
+ font-size: 15px;
80
+ line-height: 27px;
81
+ margin-top: 2em;
82
+ margin-bottom: 2em;
83
+ }
84
+
85
+ p.admonition-title {
86
+ font-size: 15px !important;
87
+ line-height: 20px !important;
88
+ }
89
+
90
+ article > li > a {
91
+ font-size: 19px;
92
+ line-height: 29px;
93
+ }
94
+
95
+ div.tab-set {
96
+ margin-top: 1em;
97
+ margin-bottom: 2em;
98
+ }
99
+
100
+ div.tab-set pre {
101
+ padding: 1.25em;
102
+ }
103
+
104
+ body .highlight.only_dark {
105
+ background: #18181a;
106
+ }
tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-700.woff ADDED
Binary file (30.4 kB). View file
 
tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-700.woff2 ADDED
Binary file (25.7 kB). View file
 
tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-700italic.woff ADDED
Binary file (32.3 kB). View file
 
tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-700italic.woff2 ADDED
Binary file (27.8 kB). View file
 
tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-italic.woff ADDED
Binary file (31.5 kB). View file
 
tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-italic.woff2 ADDED
Binary file (26.6 kB). View file
 
tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-regular.woff ADDED
Binary file (32.2 kB). View file
 
tasks/tasksmith-c756db832cf4/tests/source/docs/_static/fonts/ubuntu-mono-v15-latin-regular.woff2 ADDED
Binary file (27.4 kB). View file
 
tasks/tasksmith-c756db832cf4/tests/source/docs/basics.md ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The Basics
2
+ ```{currentmodule} cattrs
3
+ ```
4
+
5
+ All _cattrs_ functionality is exposed through a {class}`cattrs.Converter` object.
6
+ A global converter is provided for convenience as {data}`cattrs.global_converter`
7
+ but more complex customizations should be performed on private instances, any number of which can be made.
8
+
9
+
10
+ ## Converters and Hooks
11
+
12
+ The core functionality of a converter is structuring and unstructuring data by composing [provided](defaulthooks.md) and [custom handling functions](customizing.md), called _hooks_.
13
+
14
+ To create a private converter, instantiate a {class}`cattrs.Converter`. Converters are relatively cheap; users are encouraged to have as many as they need.
15
+
16
+ The two main methods, {meth}`structure <cattrs.BaseConverter.structure>` and {meth}`unstructure <cattrs.BaseConverter.unstructure>`, are used to convert between _structured_ and _unstructured_ data.
17
+
18
+ ```{doctest} basics
19
+ >>> from cattrs import structure, unstructure
20
+ >>> from attrs import define
21
+
22
+ >>> @define
23
+ ... class Model:
24
+ ... a: int
25
+
26
+ >>> unstructure(Model(1))
27
+ {'a': 1}
28
+ >>> structure({"a": 1}, Model)
29
+ Model(a=1)
30
+ ```
31
+
32
+ _cattrs_ comes with a rich library of un/structuring hooks by default but it excels at composing custom hooks with built-in ones.
33
+
34
+ The simplest approach to customization is writing a new hook from scratch.
35
+ For example, we can write our own hook for the `int` class and register it to a converter.
36
+
37
+ ```{doctest} basics
38
+ >>> from cattrs import Converter
39
+
40
+ >>> converter = Converter()
41
+
42
+ >>> @converter.register_structure_hook
43
+ ... def int_hook(value, type) -> int:
44
+ ... if not isinstance(value, int):
45
+ ... raise ValueError('not an int!')
46
+ ... return value
47
+ ```
48
+
49
+ Now, any other hook converting an `int` will use it.
50
+
51
+ Another approach to customization is wrapping (composing) an existing hook with your own function.
52
+ A base hook can be obtained from a converter and then be subjected to the very rich machinery of function composition that Python offers.
53
+
54
+
55
+ ```{doctest} basics
56
+ >>> base_hook = converter.get_structure_hook(Model)
57
+
58
+ >>> @converter.register_structure_hook
59
+ ... def my_model_hook(value, type) -> Model:
60
+ ... # Apply any preprocessing to the value.
61
+ ... result = base_hook(value, type)
62
+ ... # Apply any postprocessing to the model.
63
+ ... return result
64
+ ```
65
+
66
+ (`cattrs.structure({}, Model)` is equivalent to `cattrs.get_structure_hook(Model)({}, Model)`.)
67
+
68
+ Now if we use this hook to structure a `Model`, through ✨the magic of function composition✨ that hook will use our old `int_hook`.
69
+
70
+ ```python
71
+ >>> converter.structure({"a": "1"}, Model)
72
+ + Exception Group Traceback (most recent call last):
73
+ | File "...", line 22, in <module>
74
+ | base_hook({"a": "1"}, Model)
75
+ | File "<cattrs generated structure __main__.Model>", line 9, in structure_Model
76
+ | cattrs.errors.ClassValidationError: While structuring Model (1 sub-exception)
77
+ +-+---------------- 1 ----------------
78
+ | Traceback (most recent call last):
79
+ | File "<cattrs generated structure __main__.Model>", line 5, in structure_Model
80
+ | File "...", line 15, in my_int_hook
81
+ | raise ValueError("not an int!")
82
+ | ValueError: not an int!
83
+ | Structuring class Model @ attribute a
84
+ +------------------------------------
85
+ ```
86
+
87
+ To continue reading about customizing _cattrs_, see [](customizing.md).
88
+ More advanced structuring customizations are commonly called [](strategies.md).
89
+
90
+ ## Global Converter
91
+
92
+ Global _cattrs_ functions, such as {meth}`cattrs.structure`, use a single {data}`global converter <cattrs.global_converter>`.
93
+ Changes done to this global converter, such as registering new structure and unstructure hooks, affect all code using the global functions.
94
+
95
+ The following functions implicitly use this global converter:
96
+
97
+ - {meth}`cattrs.structure`
98
+ - {meth}`cattrs.unstructure`
99
+ - {meth}`cattrs.get_structure_hook`
100
+ - {meth}`cattrs.get_unstructure_hook`
101
+ - {meth}`cattrs.structure_attrs_fromtuple`
102
+ - {meth}`cattrs.structure_attrs_fromdict`
103
+
104
+ Changes made to the global converter will affect the behavior of these functions.
105
+
106
+ Larger applications are strongly encouraged to create and customize different, private instances of {class}`cattrs.Converter`.
tasks/tasksmith-c756db832cf4/tests/source/docs/benchmarking.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Benchmarking
2
+
3
+ cattrs includes a benchmarking suite to help detect performance regressions and
4
+ guide performance optimizations.
5
+
6
+ The suite is based on pytest and pytest-benchmark. Benchmarks are similar to
7
+ tests, with the exception of being stored in the `bench/` directory and being
8
+ used to verify performance instead of correctness.
9
+
10
+ ## A Sample Workflow
11
+
12
+ First, ensure the system you're benchmarking on is as stable as possible. For
13
+ example, the pyperf library has a `system tune` command that can tweak
14
+ CPU frequency governors. You also might want to quit as many applications as
15
+ possible and run the benchmark suite on isolated CPU cores (`taskset` can be
16
+ used for this purpose on Linux).
17
+
18
+ Then, generate a baseline using `make bench`. This will run the benchmark suite
19
+ and save it into a file.
20
+
21
+ Following that, implement the changes you have in mind. Run the test suite to
22
+ ensure correctness. Then, compare the performance of the new code to the saved
23
+ baseline using `make bench-cmp`. If the code is still correct but faster,
24
+ congratulations!
tasks/tasksmith-c756db832cf4/tests/source/docs/cattrs.gen.rst ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cattrs.gen package
2
+ ==================
3
+
4
+ .. automodule:: cattrs.gen
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
8
+
9
+ Submodules
10
+ ----------
11
+
12
+ cattrs.gen.typeddicts module
13
+ ----------------------------
14
+
15
+ .. automodule:: cattrs.gen.typeddicts
16
+ :members:
17
+ :undoc-members:
18
+ :show-inheritance:
tasks/tasksmith-c756db832cf4/tests/source/docs/cattrs.preconf.rst ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cattrs.preconf package
2
+ ======================
3
+
4
+ .. automodule:: cattrs.preconf
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
8
+
9
+ Submodules
10
+ ----------
11
+
12
+ cattrs.preconf.bson module
13
+ --------------------------
14
+
15
+ .. automodule:: cattrs.preconf.bson
16
+ :members:
17
+ :undoc-members:
18
+ :show-inheritance:
19
+
20
+ cattrs.preconf.cbor2 module
21
+ ---------------------------
22
+
23
+ .. automodule:: cattrs.preconf.cbor2
24
+ :members:
25
+ :undoc-members:
26
+ :show-inheritance:
27
+
28
+ cattrs.preconf.json module
29
+ --------------------------
30
+
31
+ .. automodule:: cattrs.preconf.json
32
+ :members:
33
+ :undoc-members:
34
+ :show-inheritance:
35
+
36
+ cattrs.preconf.msgpack module
37
+ -----------------------------
38
+
39
+ .. automodule:: cattrs.preconf.msgpack
40
+ :members:
41
+ :undoc-members:
42
+ :show-inheritance:
43
+
44
+ cattrs.preconf.msgspec module
45
+ -----------------------------
46
+
47
+ .. automodule:: cattrs.preconf.msgspec
48
+ :members:
49
+ :undoc-members:
50
+ :show-inheritance:
51
+
52
+ cattrs.preconf.orjson module
53
+ ----------------------------
54
+
55
+ .. automodule:: cattrs.preconf.orjson
56
+ :members:
57
+ :undoc-members:
58
+ :show-inheritance:
59
+
60
+ cattrs.preconf.pyyaml module
61
+ ----------------------------
62
+
63
+ .. automodule:: cattrs.preconf.pyyaml
64
+ :members:
65
+ :undoc-members:
66
+ :show-inheritance:
67
+
68
+ cattrs.preconf.tomlkit module
69
+ -----------------------------
70
+
71
+ .. automodule:: cattrs.preconf.tomlkit
72
+ :members:
73
+ :undoc-members:
74
+ :show-inheritance:
75
+
76
+ cattrs.preconf.tomllib module
77
+ -----------------------------
78
+
79
+ .. automodule:: cattrs.preconf.tomllib
80
+ :members:
81
+ :undoc-members:
82
+ :show-inheritance:
83
+
84
+ cattrs.preconf.ujson module
85
+ ---------------------------
86
+
87
+ .. automodule:: cattrs.preconf.ujson
88
+ :members:
89
+ :undoc-members:
90
+ :show-inheritance:
tasks/tasksmith-c756db832cf4/tests/source/docs/cattrs.rst ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cattrs package
2
+ ==============
3
+
4
+ .. automodule:: cattrs
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
8
+
9
+ Subpackages
10
+ -----------
11
+
12
+ .. toctree::
13
+ :maxdepth: 4
14
+
15
+ cattrs.gen
16
+ cattrs.preconf
17
+ cattrs.strategies
18
+
19
+ Submodules
20
+ ----------
21
+
22
+ cattrs.cols module
23
+ ------------------
24
+
25
+ .. automodule:: cattrs.cols
26
+ :members:
27
+ :undoc-members:
28
+ :show-inheritance:
29
+
30
+ cattrs.disambiguators module
31
+ ----------------------------
32
+
33
+ .. automodule:: cattrs.disambiguators
34
+ :members:
35
+ :undoc-members:
36
+ :show-inheritance:
37
+
38
+ cattrs.dispatch module
39
+ ----------------------
40
+
41
+ .. automodule:: cattrs.dispatch
42
+ :members:
43
+ :undoc-members:
44
+ :show-inheritance:
45
+
46
+ cattrs.errors module
47
+ --------------------
48
+
49
+ .. automodule:: cattrs.errors
50
+ :members:
51
+ :undoc-members:
52
+ :show-inheritance:
53
+
54
+ cattrs.fns module
55
+ -----------------
56
+
57
+ .. automodule:: cattrs.fns
58
+ :members:
59
+ :undoc-members:
60
+ :show-inheritance:
61
+
62
+ cattrs.v module
63
+ ---------------
64
+
65
+ .. automodule:: cattrs.v
66
+ :members:
67
+ :undoc-members:
68
+ :show-inheritance:
tasks/tasksmith-c756db832cf4/tests/source/docs/cattrs.strategies.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ cattrs.strategies package
2
+ =========================
3
+
4
+ .. automodule:: cattrs.strategies
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
tasks/tasksmith-c756db832cf4/tests/source/docs/conf.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cattrs documentation build configuration file, created by
2
+ # sphinx-quickstart on Tue Jul 9 22:26:36 2013.
3
+ #
4
+ # This file is execfile()d with the current directory set to its
5
+ # containing dir.
6
+ #
7
+ # Note that not all possible configuration values are present in this
8
+ # autogenerated file.
9
+ #
10
+ # All configuration values have a default; values that are commented out
11
+ # serve to show the default.
12
+
13
+ import os
14
+ import sys
15
+ from importlib.metadata import version as v
16
+
17
+ # Set canonical URL from the Read the Docs Domain
18
+ html_baseurl = os.environ.get("READTHEDOCS_CANONICAL_URL", "")
19
+
20
+ # Tell Jinja2 templates the build is running on Read the Docs
21
+ if os.environ.get("READTHEDOCS", "") == "True":
22
+ html_context = {"READTHEDOCS": True}
23
+
24
+
25
+ # If extensions (or modules to document with autodoc) are in another
26
+ # directory, add these directories to sys.path here. If the directory is
27
+ # relative to the documentation root, use os.path.abspath to make it
28
+ # absolute, like shown here.
29
+ # sys.path.insert(0, os.path.abspath('.'))
30
+
31
+ # Get the project root dir, which is the parent dir of this
32
+ cwd = os.getcwd()
33
+ project_root = os.path.join(os.path.dirname(cwd), "src")
34
+
35
+ # Insert the project root dir as the first element in the PYTHONPATH.
36
+ # This lets us ensure that the source package is imported, and that its
37
+ # version is used.
38
+ sys.path.insert(0, project_root)
39
+
40
+ # -- General configuration ---------------------------------------------
41
+
42
+ # If your documentation needs a minimal Sphinx version, state it here.
43
+ # needs_sphinx = '1.0'
44
+
45
+ # Add any Sphinx extension module names here, as strings. They can be
46
+ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
47
+ extensions = [
48
+ "sphinx.ext.autodoc",
49
+ "sphinx.ext.viewcode",
50
+ "sphinx.ext.doctest",
51
+ "sphinx_copybutton",
52
+ "myst_parser",
53
+ ]
54
+
55
+ myst_enable_extensions = ["colon_fence", "smartquotes", "deflist"]
56
+
57
+ # Add any paths that contain templates here, relative to this directory.
58
+ templates_path = ["_templates"]
59
+
60
+ # The suffix of source filenames.
61
+ source_suffix = ".rst"
62
+
63
+ # The encoding of source files.
64
+ # source_encoding = 'utf-8-sig'
65
+
66
+ # The master toctree document.
67
+ master_doc = "index"
68
+
69
+ # General information about the project.
70
+ project = "cattrs"
71
+ copyright = "2020, Tin Tvrtković"
72
+
73
+ # The version info for the project you're documenting, acts as replacement
74
+ # for |version| and |release|, also used in various other places throughout
75
+ # the built documents.
76
+ #
77
+ # The short X.Y version.
78
+ version = v("cattrs")
79
+ # The full version, including alpha/beta/rc tags.
80
+ release = version
81
+ if "dev" in release:
82
+ release = version = "UNRELEASED"
83
+
84
+ # The language for content autogenerated by Sphinx. Refer to documentation
85
+ # for a list of supported languages.
86
+ # language = None
87
+
88
+ # There are two options for replacing |today|: either, you set today to
89
+ # some non-false value, then it is used:
90
+ # today = ''
91
+ # Else, today_fmt is used as the format for a strftime call.
92
+ # today_fmt = '%B %d, %Y'
93
+
94
+ # List of patterns, relative to source directory, that match files and
95
+ # directories to ignore when looking for source files.
96
+ exclude_patterns = ["_build"]
97
+
98
+ # The reST default role (used for this markup: `text`) to use for all
99
+ # documents.
100
+ # default_role = None
101
+
102
+ # If true, '()' will be appended to :func: etc. cross-reference text.
103
+ # add_function_parentheses = True
104
+
105
+ # If true, the current module name will be prepended to all description
106
+ # unit titles (such as .. function::).
107
+ # add_module_names = True
108
+
109
+ # If true, sectionauthor and moduleauthor directives will be shown in the
110
+ # output. They are ignored by default.
111
+ # show_authors = False
112
+
113
+ # The name of the Pygments (syntax highlighting) style to use.
114
+ # pygments_style = "sphinx"
115
+
116
+ # A list of ignored prefixes for module index sorting.
117
+ # modindex_common_prefix = []
118
+
119
+ # If true, keep warnings as "system message" paragraphs in the built
120
+ # documents.
121
+ # keep_warnings = False
122
+
123
+
124
+ # -- Options for HTML output -------------------------------------------
125
+
126
+ # The theme to use for HTML and HTML Help pages. See the documentation for
127
+ # a list of builtin themes.
128
+ html_theme = "furo"
129
+ html_theme_options = {
130
+ "light_css_variables": {
131
+ "font-stack": "Inter,sans-serif",
132
+ "font-stack--monospace": "'Ubuntu Mono', monospace",
133
+ "code-font-size": "90%",
134
+ "color-highlight-on-target": "transparent",
135
+ },
136
+ "dark_css_variables": {"color-highlight-on-target": "transparent"},
137
+ }
138
+
139
+ # Add any paths that contain custom themes here, relative to this directory.
140
+ # html_theme_path = []
141
+
142
+ # The name for this set of Sphinx documents. If None, it defaults to
143
+ # "<project> v<release> documentation".
144
+ # html_title = None
145
+
146
+ # A shorter title for the navigation bar. Default is the same as
147
+ # html_title.
148
+ # html_short_title = None
149
+
150
+ # The name of an image file (relative to this directory) to place at the
151
+ # top of the sidebar.
152
+ # html_logo = None
153
+
154
+ # The name of an image file (within the static path) to use as favicon
155
+ # of the docs. This file should be a Windows icon file (.ico) being
156
+ # 16x16 or 32x32 pixels large.
157
+ # html_favicon = None
158
+
159
+ # Add any paths that contain custom static files (such as style sheets)
160
+ # here, relative to this directory. They are copied after the builtin
161
+ # static files, so a file named "default.css" will overwrite the builtin
162
+ # "default.css".
163
+ html_static_path = ["_static"]
164
+
165
+ html_css_files = ["custom.css"]
166
+
167
+ # If not '', a 'Last updated on:' timestamp is inserted at every page
168
+ # bottom, using the given strftime format.
169
+ # html_last_updated_fmt = '%b %d, %Y'
170
+
171
+ # If true, SmartyPants will be used to convert quotes and dashes to
172
+ # typographically correct entities.
173
+ # html_use_smartypants = True
174
+
175
+ # Custom sidebar templates, maps document names to template names.
176
+ # html_sidebars = {}
177
+
178
+ # Additional templates that should be rendered to pages, maps page names
179
+ # to template names.
180
+ # html_additional_pages = {}
181
+
182
+ # If false, no module index is generated.
183
+ # html_domain_indices = True
184
+
185
+ # If false, no index is generated.
186
+ # html_use_index = True
187
+
188
+ # If true, the index is split into individual pages for each letter.
189
+ # html_split_index = False
190
+
191
+ # If true, links to the reST sources are added to the pages.
192
+ # html_show_sourcelink = True
193
+
194
+ # If true, "Created using Sphinx" is shown in the HTML footer.
195
+ # Default is True.
196
+ # html_show_sphinx = True
197
+
198
+ # If true, "(C) Copyright ..." is shown in the HTML footer.
199
+ # Default is True.
200
+ # html_show_copyright = True
201
+
202
+ # If true, an OpenSearch description file will be output, and all pages
203
+ # will contain a <link> tag referring to it. The value of this option
204
+ # must be the base URL from which the finished HTML is served.
205
+ # html_use_opensearch = ''
206
+
207
+ # This is the file name suffix for HTML files (e.g. ".xhtml").
208
+ # html_file_suffix = None
209
+
210
+ # Output file base name for HTML help builder.
211
+ htmlhelp_basename = "cattrsdoc"
212
+
213
+
214
+ # -- Options for LaTeX output ------------------------------------------
215
+
216
+ latex_elements = {
217
+ # The paper size ('letterpaper' or 'a4paper').
218
+ # 'papersize': 'letterpaper',
219
+ # The font size ('10pt', '11pt' or '12pt').
220
+ # 'pointsize': '10pt',
221
+ # Additional stuff for the LaTeX preamble.
222
+ # 'preamble': '',
223
+ }
224
+
225
+ # Grouping the document tree into LaTeX files. List of tuples
226
+ # (source start file, target name, title, author, documentclass
227
+ # [howto/manual]).
228
+ latex_documents = [
229
+ ("index", "cattrs.tex", "cattrs Documentation", "Tin Tvrtković", "manual")
230
+ ]
231
+
232
+ # The name of an image file (relative to this directory) to place at
233
+ # the top of the title page.
234
+ # latex_logo = None
235
+
236
+ # For "manual" documents, if this is true, then toplevel headings
237
+ # are parts, not chapters.
238
+ # latex_use_parts = False
239
+
240
+ # If true, show page references after internal links.
241
+ # latex_show_pagerefs = False
242
+
243
+ # If true, show URL addresses after external links.
244
+ # latex_show_urls = False
245
+
246
+ # Documents to append as an appendix to all manuals.
247
+ # latex_appendices = []
248
+
249
+ # If false, no module index is generated.
250
+ # latex_domain_indices = True
251
+
252
+
253
+ # -- Options for manual page output ------------------------------------
254
+
255
+ # One entry per manual page. List of tuples
256
+ # (source start file, name, description, authors, manual section).
257
+ man_pages = [("index", "cattrs", "cattrs Documentation", ["Tin Tvrtković"], 1)]
258
+
259
+ # If true, show URL addresses after external links.
260
+ # man_show_urls = False
261
+
262
+
263
+ # -- Options for Texinfo output ----------------------------------------
264
+
265
+ # Grouping the document tree into Texinfo files. List of tuples
266
+ # (source start file, target name, title, author,
267
+ # dir menu entry, description, category)
268
+ texinfo_documents = [
269
+ (
270
+ "index",
271
+ "cattrs",
272
+ "cattrs Documentation",
273
+ "Tin Tvrtković",
274
+ "cattrs",
275
+ "Composable complex class support for attrs.",
276
+ "Miscellaneous",
277
+ )
278
+ ]
279
+
280
+ # Documents to append as an appendix to all manuals.
281
+ # texinfo_appendices = []
282
+
283
+ # If false, no module index is generated.
284
+ # texinfo_domain_indices = True
285
+
286
+ # How to display URL addresses: 'footnote', 'no', or 'inline'.
287
+ # texinfo_show_urls = 'footnote'
288
+
289
+ # If true, do not generate a @detailmenu in the "Top" node's menu.
290
+ # texinfo_no_detailmenu = False
291
+
292
+ doctest_global_setup = (
293
+ "import attr, cattr, cattrs;"
294
+ "from attr import Factory, define, field;"
295
+ "from cattrs import Converter;"
296
+ "from typing import *;"
297
+ "from enum import Enum, unique"
298
+ )
299
+ autodoc_member_order = "bysource"
300
+ autodoc_typehints = "description"
301
+ autosectionlabel_prefix_document = True
302
+ copybutton_prompt_text = r">>> |\.\.\. "
303
+ copybutton_prompt_is_regexp = True
304
+ myst_heading_anchors = 3
305
+ autoclass_content = "both"
tasks/tasksmith-c756db832cf4/tests/source/docs/contributing.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ```{include} ../CONTRIBUTING.md
2
+
3
+ ```
tasks/tasksmith-c756db832cf4/tests/source/docs/customizing.md ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Customizing (Un-)structuring
2
+
3
+ This section describes customizing the unstructuring and structuring processes in _cattrs_.
4
+
5
+ As you go about customizing converters by registering hooks and hook factories,
6
+ keep in mind that **the order of hook registration matters**.
7
+
8
+ Technically speaking, whether the order matters or not depends on the actual implementation of hook factories used.
9
+ In practice, the built-in _cattrs_ hooks are optimized to perform early resolution of hooks.
10
+ You will likely compose with these hook factories.
11
+
12
+ This means that **hooks for simpler types should be registered first**.
13
+ For example, to override hooks for structuring `int` and `list[int]`, the hook for `int`
14
+ must be registered first.
15
+ When the {meth}`list_structure_factory() <cattrs.cols.list_structure_factory>`
16
+ is applied to the `list[int]` type to produce a hook, it will retrieve and store
17
+ the hook for `int`, which should be already present.
18
+
19
+ ## Custom (Un-)structuring Hooks
20
+
21
+ You can write your own structuring and unstructuring functions and register them for types using {meth}`Converter.register_structure_hook() <cattrs.BaseConverter.register_structure_hook>` and {meth}`Converter.register_unstructure_hook() <cattrs.BaseConverter.register_unstructure_hook>`.
22
+
23
+ {meth}`register_structure_hook() <cattrs.BaseConverter.register_structure_hook>` and {meth}`register_unstructure_hook() <cattrs.BaseConverter.register_unstructure_hook>` use a Python [_singledispatch_](https://docs.python.org/3/library/functools.html#functools.singledispatch) under the hood.
24
+ _singledispatch_ is powerful and fast but comes with some limitations; namely that it performs checks using `issubclass()` which doesn't work with many Python types.
25
+ Some examples of this are:
26
+
27
+ - various generic collections (`list[int]` is not a _subclass_ of `list`)
28
+ - literals (`Literal[1]` is not a _subclass_ of `Literal[1]`)
29
+ - generics (`MyClass[int]` is not a _subclass_ of `MyClass`)
30
+ - protocols, unless they are `runtime_checkable`
31
+ - various modifiers, such as `Final` and `NotRequired`
32
+ - `typing.Annotated`
33
+
34
+ ... and many others. In these cases, [predicate hooks](#predicate-hooks) should be used instead.
35
+
36
+ Even though unions, [newtypes](https://docs.python.org/3/library/typing.html#newtype)
37
+ and [modern type aliases](https://docs.python.org/3/library/typing.html#type-aliases)
38
+ do not work with _singledispatch_,
39
+ these methods have special support for these type forms and can be used with them.
40
+ Instead of using _singledispatch_, predicate hooks will automatically be used instead.
41
+
42
+ ### Use as Decorators
43
+
44
+ {meth}`register_structure_hook() <cattrs.BaseConverter.register_structure_hook>` and {meth}`register_unstructure_hook() <cattrs.BaseConverter.register_unstructure_hook>` can also be used as _decorators_.
45
+ When used this way they behave a little differently.
46
+
47
+ {meth}`register_structure_hook() <cattrs.BaseConverter.register_structure_hook>` will inspect the return type of the hook and register the hook for that type.
48
+
49
+ ```python
50
+ @converter.register_structure_hook
51
+ def my_int_hook(val: Any, _) -> int:
52
+ """This hook will be registered for `int`s."""
53
+ return int(val)
54
+ ```
55
+
56
+ {meth}`register_unstructure_hook() <cattrs.BaseConverter.register_unstructure_hook>` will inspect the type of the first argument and register the hook for that type.
57
+
58
+ ```python
59
+ from datetime import datetime
60
+
61
+ @converter.register_unstructure_hook
62
+ def my_datetime_hook(val: datetime) -> str:
63
+ """This hook will be registered for `datetime`s."""
64
+ return val.isoformat()
65
+ ```
66
+
67
+ The non-decorator approach is still recommended when dealing with lambdas, hooks produced elsewhere, unannotated hooks and situations where type introspection doesn't work.
68
+
69
+ ```{versionadded} 24.1.0
70
+
71
+ ```
72
+
73
+ ### Predicate Hooks
74
+
75
+ A _predicate_ is a function that takes a type and returns true or false
76
+ depending on whether the associated hook can handle the given type.
77
+
78
+ The {meth}`register_unstructure_hook_func() <cattrs.BaseConverter.register_unstructure_hook_func>` and {meth}`register_structure_hook_func() <cattrs.BaseConverter.register_structure_hook_func>` are used
79
+ to link un/structuring hooks to arbitrary types. These hooks are then called _predicate hooks_, and are very powerful.
80
+
81
+ Predicate hooks are evaluated after the _singledispatch_ hooks.
82
+ In the case where both a _singledispatch_ hook and a predicate hook are present, the _singledispatch_ hook will be used.
83
+ Predicate hooks are checked in reverse order of registration, one-by-one, until a match is found.
84
+
85
+ The following example demonstrates a predicate that checks for the presence of an attribute on a class (`custom`), and then overrides the structuring logic.
86
+
87
+ ```{doctest}
88
+
89
+ >>> class D:
90
+ ... custom = True
91
+ ... def __init__(self, a):
92
+ ... self.a = a
93
+ ... def __repr__(self):
94
+ ... return f'D(a={self.a})'
95
+ ... @classmethod
96
+ ... def deserialize(cls, data):
97
+ ... return cls(data["a"])
98
+
99
+ >>> cattrs.register_structure_hook_func(
100
+ ... lambda cls: getattr(cls, "custom", False), lambda d, t: t.deserialize(d)
101
+ ... )
102
+
103
+ >>> cattrs.structure({'a': 2}, D)
104
+ D(a=2)
105
+ ```
106
+
107
+ ### Hook Factories
108
+
109
+ Hook factories are higher-order predicate hooks: they are functions that _produce_ hooks.
110
+ Hook factories are commonly used to create very optimized hooks by offloading part of the work into a separate, earlier step.
111
+
112
+ Hook factories are registered using {meth}`Converter.register_unstructure_hook_factory() <cattrs.BaseConverter.register_unstructure_hook_factory>` and {meth}`Converter.register_structure_hook_factory() <cattrs.BaseConverter.register_structure_hook_factory>`.
113
+
114
+ Here's an example showing how to use hook factories to apply the `forbid_extra_keys` to all attrs classes:
115
+
116
+ ```python
117
+ >>> from attrs import define, has
118
+ >>> from cattrs import Converter
119
+ >>> from cattrs.gen import make_dict_structure_fn
120
+
121
+ >>> c = Converter()
122
+
123
+ >>> c.register_structure_hook_factory(
124
+ ... has,
125
+ ... lambda cl: make_dict_structure_fn(cl, c, _cattrs_forbid_extra_keys=True)
126
+ ... )
127
+
128
+ >>> @define
129
+ ... class E:
130
+ ... an_int: int
131
+
132
+ >>> c.structure({"an_int": 1, "else": 2}, E)
133
+ Traceback (most recent call last):
134
+ ...
135
+ cattrs.errors.ForbiddenExtraKeysError: Extra fields in constructor for E: else
136
+ ```
137
+
138
+ Hook factories can receive the current converter by exposing an additional required parameter.
139
+
140
+ A complex use case for hook factories is described over at [](usage.md#using-factory-hooks).
141
+
142
+ #### Use as Decorators
143
+
144
+ {meth}`register_unstructure_hook_factory() <cattrs.BaseConverter.register_unstructure_hook_factory>` and
145
+ {meth}`register_structure_hook_factory() <cattrs.BaseConverter.register_structure_hook_factory>` can also be used as decorators.
146
+
147
+ Here's an example of using an unstructure hook factory to handle unstructuring [queues](https://docs.python.org/3/library/queue.html#queue.Queue).
148
+
149
+ ```{doctest}
150
+ >>> from collections.abc import Callable
151
+ >>> from queue import Queue
152
+ >>> from typing import Any, get_args, get_origin
153
+ >>> from cattrs import Converter
154
+
155
+ >>> c = Converter()
156
+
157
+ >>> @c.register_unstructure_hook_factory(lambda t: get_origin(t) is Queue)
158
+ ... def queue_hook_factory(cl: Any, converter: Converter) -> Callable:
159
+ ... type_arg = get_args(cl)[0]
160
+ ... elem_handler = converter.get_unstructure_hook(type_arg)
161
+ ...
162
+ ... def unstructure_hook(v: Queue) -> list:
163
+ ... res = []
164
+ ... while not v.empty():
165
+ ... res.append(elem_handler(v.get_nowait()))
166
+ ... return res
167
+ ...
168
+ ... return unstructure_hook
169
+
170
+ >>> q = Queue()
171
+ >>> q.put(1)
172
+ >>> q.put(2)
173
+
174
+ >>> c.unstructure(q, unstructure_as=Queue[int])
175
+ [1, 2]
176
+ ```
177
+
178
+ ## Using `cattrs.gen` Hook Factories
179
+
180
+ The {mod}`cattrs.gen` module contains [hook factories](#hook-factories) for un/structuring _attrs_ classes, dataclasses and typed dicts.
181
+ The default {class}`Converter <cattrs.Converter>`, upon first encountering one of these types,
182
+ will use the hook factories mentioned here to generate specialized hooks for it,
183
+ register the hooks and use them.
184
+
185
+ One reason for generating these hooks in advance is that they can bypass a lot of _cattrs_ machinery and be significantly faster than normal _cattrs_.
186
+ The hook factories are also good building blocks for more complex customizations.
187
+
188
+ Another reason is overriding behavior on a per-attribute basis.
189
+
190
+ Currently, the overrides only support generating dictionary un/structuring hooks (as opposed to tuples),
191
+ and support `omit_if_default`, `forbid_extra_keys`, `rename` and `omit`.
192
+
193
+ ### `omit_if_default`
194
+ ```{currentmodule} cattrs.gen
195
+ ```
196
+
197
+ This override can be applied on a per-class or per-attribute basis.
198
+ The generated unstructuring hook will skip unstructuring values that are equal to their default or factory values.
199
+
200
+ ```{doctest}
201
+
202
+ >>> from cattrs.gen import make_dict_unstructure_fn, override
203
+
204
+ >>> @define
205
+ ... class WithDefault:
206
+ ... a: int
207
+ ... b: dict = Factory(dict)
208
+
209
+ >>> c = cattrs.Converter()
210
+ >>> c.register_unstructure_hook(
211
+ ... WithDefault,
212
+ ... make_dict_unstructure_fn(WithDefault, c, b=override(omit_if_default=True)),
213
+ ... )
214
+ >>> c.unstructure(WithDefault(1))
215
+ {'a': 1}
216
+ ```
217
+
218
+ Note that the per-attribute value overrides the per-class value.
219
+ A side-effect of this is the ability to force the presence of a subset of fields.
220
+ For example, consider a class with a `dateTime` field and a factory for it: skipping the unstructuring of the `dateTime` field would be inconsistent and based on the current time.
221
+ So we apply the `omit_if_default` rule to the class, but not to the `dateTime` field.
222
+
223
+ ```{note}
224
+ The parameter to {meth}`make_dict_unstructure_fn` is named ``_cattrs_omit_if_default`` instead of just ``omit_if_default`` to avoid potential collisions with an override for a field named ``omit_if_default``.
225
+ ```
226
+
227
+ ```{doctest}
228
+
229
+ >>> from datetime import datetime
230
+ >>> from cattrs.gen import make_dict_unstructure_fn, override
231
+
232
+ >>> @define
233
+ ... class TestClass:
234
+ ... a: int | None = None
235
+ ... b: datetime = Factory(datetime.utcnow)
236
+
237
+ >>> c = cattrs.Converter()
238
+ >>> hook = make_dict_unstructure_fn(
239
+ ... TestClass,
240
+ ... c,
241
+ ... _cattrs_omit_if_default=True,
242
+ ... b=override(omit_if_default=False)
243
+ ... )
244
+ >>> c.register_unstructure_hook(TestClass, hook)
245
+ >>> c.unstructure(TestClass())
246
+ {'b': ...}
247
+ ```
248
+
249
+ This override has no effect when generating structuring functions.
250
+
251
+ ### `forbid_extra_keys`
252
+
253
+ By default _cattrs_ is lenient in accepting unstructured input.
254
+ If extra keys are present in a dictionary, they will be ignored when generating a structured object.
255
+ Sometimes it may be desirable to enforce a stricter contract, and to raise an error when unknown keys are present - in particular when fields have default values this may help with catching typos.
256
+ `forbid_extra_keys` can also be enabled (or disabled) on a per-class basis when creating structure hooks with {meth}`make_dict_structure_fn() <cattrs.gen.make_dict_structure_fn>`.
257
+
258
+ ```{doctest}
259
+ :options: +SKIP
260
+
261
+ >>> from cattrs.gen import make_dict_structure_fn
262
+ >>>
263
+ >>> @define
264
+ ... class TestClass:
265
+ ... number: int = 1
266
+ >>>
267
+ >>> c = cattrs.Converter(forbid_extra_keys=True)
268
+ >>> c.structure({"nummber": 2}, TestClass)
269
+ Traceback (most recent call last):
270
+ ...
271
+ ForbiddenExtraKeyError: Extra fields in constructor for TestClass: nummber
272
+ >>> hook = make_dict_structure_fn(TestClass, c, _cattrs_forbid_extra_keys=False)
273
+ >>> c.register_structure_hook(TestClass, hook)
274
+ >>> c.structure({"nummber": 2}, TestClass)
275
+ TestClass(number=1)
276
+ ```
277
+
278
+ This behavior can only be applied to classes or to the default for the {class}`Converter <cattrs.Converter>`, and has no effect when generating unstructuring functions.
279
+
280
+ ```{versionchanged} 23.2.0
281
+ The value for the `make_dict_structure_fn._cattrs_forbid_extra_keys` parameter is now taken from the given converter by default.
282
+ ```
283
+
284
+ ### `rename`
285
+
286
+ Using the rename override makes `cattrs` use the provided name instead of the real attribute name.
287
+ This is useful if an attribute name is a reserved keyword in Python.
288
+
289
+ ```{doctest}
290
+
291
+ >>> from pendulum import DateTime
292
+ >>> from cattrs.gen import make_dict_unstructure_fn, make_dict_structure_fn, override
293
+
294
+ >>> @define
295
+ ... class ExampleClass:
296
+ ... klass: int | None
297
+
298
+ >>> c = cattrs.Converter()
299
+ >>> unst_hook = make_dict_unstructure_fn(ExampleClass, c, klass=override(rename="class"))
300
+ >>> st_hook = make_dict_structure_fn(ExampleClass, c, klass=override(rename="class"))
301
+ >>> c.register_unstructure_hook(ExampleClass, unst_hook)
302
+ >>> c.register_structure_hook(ExampleClass, st_hook)
303
+ >>> c.unstructure(ExampleClass(1))
304
+ {'class': 1}
305
+ >>> c.structure({'class': 1}, ExampleClass)
306
+ ExampleClass(klass=1)
307
+ ```
308
+
309
+ ### `omit`
310
+
311
+ This override can only be applied to individual attributes.
312
+ Using the `omit` override will simply skip the attribute completely when generating a structuring or unstructuring function.
313
+
314
+ ```{doctest}
315
+
316
+ >>> from cattrs.gen import make_dict_unstructure_fn, override
317
+ >>>
318
+ >>> @define
319
+ ... class ExampleClass:
320
+ ... an_int: int
321
+ >>>
322
+ >>> c = cattrs.Converter()
323
+ >>> unst_hook = make_dict_unstructure_fn(ExampleClass, c, an_int=override(omit=True))
324
+ >>> c.register_unstructure_hook(ExampleClass, unst_hook)
325
+ >>> c.unstructure(ExampleClass(1))
326
+ {}
327
+ ```
328
+
329
+ ### `struct_hook` and `unstruct_hook`
330
+
331
+ By default, the generators will determine the right un/structure hook for each attribute of a class at time of generation according to the type of each individual attribute.
332
+
333
+ This process can be overriden by passing in the desired un/structure hook manually.
334
+
335
+ ```{doctest}
336
+
337
+ >>> from cattrs.gen import make_dict_structure_fn, override
338
+
339
+ >>> @define
340
+ ... class ExampleClass:
341
+ ... an_int: int
342
+
343
+ >>> c = cattrs.Converter()
344
+ >>> st_hook = make_dict_structure_fn(
345
+ ... ExampleClass, c, an_int=override(struct_hook=lambda v, _: v + 1)
346
+ ... )
347
+ >>> c.register_structure_hook(ExampleClass, st_hook)
348
+
349
+ >>> c.structure({"an_int": 1}, ExampleClass)
350
+ ExampleClass(an_int=2)
351
+ ```
352
+
353
+ ### `use_alias`
354
+
355
+ By default, fields are un/structured to and from dictionary keys exactly matching the field names.
356
+ _attrs_ classes support _attrs_ field aliases, which override the `__init__` parameter name for a given field.
357
+ By generating your un/structure function with `_cattrs_use_alias=True`, _cattrs_ will use the field alias instead of the field name as the un/structured dictionary key.
358
+
359
+ ```{doctest}
360
+
361
+ >>> from cattrs.gen import make_dict_structure_fn
362
+ >>>
363
+ >>> @define
364
+ ... class AliasClass:
365
+ ... number: int = field(default=1, alias="count")
366
+ >>>
367
+ >>> c = cattrs.Converter()
368
+ >>> hook = make_dict_structure_fn(AliasClass, c, _cattrs_use_alias=True)
369
+ >>> c.register_structure_hook(AliasClass, hook)
370
+ >>> c.structure({"count": 2}, AliasClass)
371
+ AliasClass(number=2)
372
+ ```
373
+
374
+ ```{versionadded} 23.2.0
375
+
376
+ ```
377
+
378
+ ### `include_init_false`
379
+
380
+ By default, _attrs_ fields defined as `init=False` are skipped when un/structuring.
381
+ By generating your un/structure function with `_cattrs_include_init_false=True`, all `init=False` fields will be included for un/structuring.
382
+
383
+ ```{doctest}
384
+
385
+ >>> from cattrs.gen import make_dict_structure_fn
386
+ >>>
387
+ >>> @define
388
+ ... class ClassWithInitFalse:
389
+ ... number: int = field(default=1, init=False)
390
+ >>>
391
+ >>> c = cattrs.Converter()
392
+ >>> hook = make_dict_structure_fn(ClassWithInitFalse, c, _cattrs_include_init_false=True)
393
+ >>> c.register_structure_hook(ClassWithInitFalse, hook)
394
+ >>> c.structure({"number": 2}, ClassWithInitFalse)
395
+ ClassWithInitFalse(number=2)
396
+ ```
397
+
398
+ A single attribute can be included by overriding it with `omit=False`.
399
+
400
+ ```{doctest}
401
+
402
+ >>> c = cattrs.Converter()
403
+ >>> hook = make_dict_structure_fn(ClassWithInitFalse, c, number=override(omit=False))
404
+ >>> c.register_structure_hook(ClassWithInitFalse, hook)
405
+ >>> c.structure({"number": 2}, ClassWithInitFalse)
406
+ ClassWithInitFalse(number=2)
407
+ ```
408
+
409
+ ```{versionadded} 23.2.0
410
+
411
+ ```
412
+
413
+ ## Using `typing.Annotated[T, override(...)]`
414
+
415
+ The un/structuring process for _attrs_ classes, dataclasses, TypedDicts and dict NamedTuples can be customized by annotating the fields using `typing.Annotated[T, override()]`.
416
+
417
+ ```{doctest}
418
+ >>> from typing import Annotated
419
+
420
+ >>> @define
421
+ ... class ExampleClass:
422
+ ... klass: Annotated[int, cattrs.override(rename="class")]
423
+
424
+ >>> cattrs.unstructure(ExampleClass(1))
425
+ {'class': 1}
426
+ >>> cattrs.structure({'class': 1}, ExampleClass)
427
+ ExampleClass(klass=1)
428
+ ```
429
+
430
+ These customizations are automatically recognized by every {class}`Converter <cattrs.Converter>`.
431
+ They can still be overriden explicitly, see [](#custom-un-structuring-hooks).
432
+
433
+ ```{attention}
434
+ One of the fundamental [design decisions](why.md#design-decisions) of _cattrs_ is that serialization rules should be separate from the models themselves;
435
+ by using this feature you're going against the spirit of this design decision.
436
+
437
+ However, software is written in many different context and with different constraints; and practicality _sometimes_ beats purity.
438
+ _Sometimes_, it's not worth introducing a mapping layer to rename one field.
439
+ _Sometimes_, you're busy prototyping and will clean up your code later.
440
+
441
+ The danger is not any single compromise, but their accumulation.
442
+ One of the most important skills as a software engineer is knowing when the cost of a trade-off has crossed the line and it's time to do things properly.
443
+ ```
444
+
445
+ ```{versionadded} 26.1.0
446
+
447
+ ```
448
+
449
+ ## Customizing Collections
450
+
451
+ ```{currentmodule} cattrs.cols
452
+
453
+ ```
454
+
455
+ The {mod}`cattrs.cols` module contains predicates and hook factories useful for customizing collection handling.
456
+ These hook factories can be wrapped to apply complex customizations.
457
+
458
+ Available predicates are:
459
+
460
+ - {meth}`is_any_set`
461
+ - {meth}`is_frozenset`
462
+ - {meth}`is_set`
463
+ - {meth}`is_mutable_sequence`
464
+ - {meth}`is_sequence`
465
+ - {meth}`is_mapping`
466
+ - {meth}`is_namedtuple`
467
+ - {meth}`is_defaultdict`
468
+
469
+ ````{tip}
470
+ These predicates aren't _cattrs_-specific and may be useful in other contexts.
471
+ ```{doctest} predicates
472
+ >>> from cattrs.cols import is_sequence
473
+
474
+ >>> is_sequence(list[str])
475
+ True
476
+ ```
477
+ ````
478
+
479
+ Available hook factories are:
480
+
481
+ - {meth}`iterable_unstructure_factory`
482
+ - {meth}`list_structure_factory`
483
+ - {meth}`homogenous_tuple_structure_factory`
484
+ - {meth}`namedtuple_structure_factory`
485
+ - {meth}`namedtuple_unstructure_factory`
486
+ - {meth}`namedtuple_dict_structure_factory`
487
+ - {meth}`namedtuple_dict_unstructure_factory`
488
+ - {meth}`mapping_structure_factory`
489
+ - {meth}`mapping_unstructure_factory`
490
+ - {meth}`defaultdict_structure_factory`
491
+
492
+ Additional predicates and hook factories will be added as requested.
493
+
494
+ For example, by default mutable sequences are structured from any iterable into lists.
495
+ This may be too lax, and additional validation may be applied by wrapping the default list structuring hook factory.
496
+
497
+ ```{testcode} list-customization
498
+ from cattrs.cols import is_mutable_sequence, list_structure_factory
499
+
500
+ c = Converter()
501
+
502
+ @c.register_structure_hook_factory(is_mutable_sequence)
503
+ def strict_list_hook_factory(type, converter):
504
+
505
+ # First, we generate the default hook...
506
+ list_hook = list_structure_factory(type, converter)
507
+
508
+ # Then, we wrap it with a function of our own...
509
+ def strict_list_hook(value, type):
510
+ if not isinstance(value, list):
511
+ raise ValueError("Not a list!")
512
+ return list_hook(value, type)
513
+
514
+ # And finally, we return our own composite hook.
515
+ return strict_list_hook
516
+ ```
517
+
518
+ Now, all mutable sequence structuring will be stricter:
519
+
520
+ ```{doctest} list-customization
521
+ >>> c.structure({"a", "b", "c"}, list[str])
522
+ Traceback (most recent call last):
523
+ ...
524
+ ValueError: Not a list!
525
+ ```
526
+
527
+ ```{versionadded} 24.1.0
528
+
529
+ ```
530
+ ```{versionchanged} 25.2.0
531
+ Added the {meth}`is_mutable_sequence` predicate and {meth}`homogenous_tuple_structure_factory` hook factory.
532
+ ```
533
+
534
+ ### Customizing Named Tuples
535
+
536
+ Named tuples can be un/structured using dictionaries using the {meth}`namedtuple_dict_structure_factory`
537
+ and {meth}`namedtuple_dict_unstructure_factory` hook factories.
538
+
539
+ To unstructure _all_ named tuples into dictionaries:
540
+
541
+ ```{doctest} namedtuples
542
+ >>> from typing import NamedTuple
543
+
544
+ >>> from cattrs.cols import is_namedtuple, namedtuple_dict_unstructure_factory
545
+ >>> c = Converter()
546
+
547
+ >>> c.register_unstructure_hook_factory(is_namedtuple, namedtuple_dict_unstructure_factory)
548
+ <function namedtuple_dict_unstructure_factory at ...>
549
+
550
+ >>> class MyNamedTuple(NamedTuple):
551
+ ... a: int
552
+
553
+ >>> c.unstructure(MyNamedTuple(1))
554
+ {'a': 1}
555
+ ```
556
+
557
+ To only un/structure _some_ named tuples into dictionaries,
558
+ change the predicate function when registering the hook factory:
559
+
560
+ ```{doctest} namedtuples
561
+ :options: +ELLIPSIS
562
+
563
+ >>> c.register_unstructure_hook_factory(
564
+ ... lambda t: t is MyNamedTuple,
565
+ ... namedtuple_dict_unstructure_factory,
566
+ ... )
567
+ <function namedtuple_dict_unstructure_factory at ...>
568
+ ```
569
+
570
+ ```{versionadded} 24.1.0
571
+
572
+ ```
tasks/tasksmith-c756db832cf4/tests/source/docs/defaulthooks.md ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Built-in Hooks
2
+
3
+ ```{currentmodule} cattrs
4
+ ```
5
+
6
+ _cattrs_ converters come with with a large repertoire of un/structuring hooks built-in.
7
+ As always, complex hooks compose with simpler ones.
8
+
9
+ ## Primitive Values
10
+
11
+ ### `int`, `float`, `str`, `bytes`
12
+
13
+ When structuring, use any of these types to coerce the object to that type.
14
+
15
+ ```{doctest}
16
+
17
+ >>> cattrs.structure(1, str)
18
+ '1'
19
+ >>> cattrs.structure("1", float)
20
+ 1.0
21
+ ```
22
+
23
+ In case the conversion isn't possible the expected exceptions will be propagated out.
24
+ The particular exceptions are the same as if you'd tried to do the coercion directly.
25
+
26
+ ```python
27
+ >>> cattrs.structure("not-an-int", int)
28
+ Traceback (most recent call last):
29
+ ...
30
+ ValueError: invalid literal for int() with base 10: 'not-an-int'
31
+ ```
32
+
33
+ Coercion is performed for performance and compatibility reasons.
34
+ Any of these hooks can be overriden if pure validation is required instead.
35
+
36
+ ```{doctest}
37
+ >>> c = Converter()
38
+
39
+ >>> @c.register_structure_hook
40
+ ... def validate(value, type) -> int:
41
+ ... if not isinstance(value, type):
42
+ ... raise ValueError(f'{value!r} not an instance of {type}')
43
+ ... return value
44
+
45
+ >>> c.structure("1", int)
46
+ Traceback (most recent call last):
47
+ ...
48
+ ValueError: '1' not an instance of <class 'int'>
49
+ ```
50
+
51
+ When unstructuring, these types are passed through unchanged.
52
+
53
+ ### Enums
54
+
55
+ Enums are structured by their values, and unstructured to their values.
56
+
57
+ ```{doctest}
58
+
59
+ >>> @unique
60
+ ... class CatBreed(Enum):
61
+ ... SIAMESE = "siamese"
62
+ ... MAINE_COON = "maine_coon"
63
+ ... SACRED_BIRMAN = "birman"
64
+
65
+ >>> cattrs.structure("siamese", CatBreed)
66
+ <CatBreed.SIAMESE: 'siamese'>
67
+
68
+ >>> cattrs.unstructure(CatBreed.SIAMESE)
69
+ 'siamese'
70
+ ```
71
+
72
+ Enum structuring and unstructuring even works for complex values, like tuples, but if you have anything but simple literal types in those tuples (`str`, `bool`, `int`, `float`) you should consider defining the Enum value's type via the `_value_` attribute's type hint so that cattrs can properly structure it. See [the Python typing documentation](https://typing.python.org/en/latest/spec/enums.html#member-values) for more information on this type hint.
73
+
74
+ ```{doctest}
75
+
76
+ >>> @unique
77
+ ... class VideoStandard(Enum):
78
+ ... NTSC = "ntsc"
79
+ ... PAL = "pal"
80
+
81
+ >>> @unique
82
+ ... class Resolution(Enum):
83
+ ... _value_: tuple[VideoStandard, int]
84
+ ... NTSC_0 = (VideoStandard.NTSC, 0)
85
+ ... PAL_0 = (VideoStandard.PAL, 0)
86
+ ... NTSC_1 = (VideoStandard.NTSC, 1)
87
+ ... PAL_1 = (VideoStandard.PAL, 1)
88
+
89
+ >>> cattrs.structure(("ntsc", 1), Resolution)
90
+ <Resolution.NTSC_1: (<VideoStandard.NTSC: 'ntsc'>, 1)>
91
+
92
+ >>> cattrs.unstructure(Resolution.PAL_0)
93
+ ['pal', 0]
94
+ ```
95
+
96
+ Again, in case of errors, the expected exceptions are raised.
97
+
98
+ ### `pathlib.Path`
99
+
100
+ [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) objects are structured using their string value,
101
+ and unstructured into their string value.
102
+
103
+ ```{doctest}
104
+ >>> from pathlib import Path
105
+
106
+ >>> cattrs.structure("/root", Path)
107
+ PosixPath('/root')
108
+
109
+ >>> cattrs.unstructure(Path("/root"))
110
+ '/root'
111
+ ```
112
+
113
+ In case the conversion isn't possible, the resulting exception is propagated out.
114
+
115
+ ```{versionadded} 23.1.0
116
+
117
+ ```
118
+
119
+
120
+ ## Collections and Related Generics
121
+
122
+
123
+ ### Optionals
124
+
125
+ `Optional` primitives and collections are supported out of the box.
126
+ [PEP 604](https://peps.python.org/pep-0604/) optionals (`T | None`) are also supported on Python 3.10 and later.
127
+
128
+ ```{doctest}
129
+
130
+ >>> cattrs.structure(None, int)
131
+ Traceback (most recent call last):
132
+ ...
133
+ TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
134
+
135
+ >>> print(cattrs.structure(None, int | None))
136
+ None
137
+ ```
138
+
139
+ Bare `Optional` s (non-parameterized, just `Optional`, as opposed to `Optional[str]`) aren't supported; `Optional[Any]` should be used instead.
140
+
141
+ `Optionals` handling can be customized using {meth}`register_structure_hook` and {meth}`register_unstructure_hook`.
142
+
143
+ ```{doctest}
144
+ >>> converter = Converter()
145
+
146
+ >>> @converter.register_structure_hook
147
+ ... def hook(val: Any, type: Any) -> str | None:
148
+ ... if val in ("", None):
149
+ ... return None
150
+ ... return str(val)
151
+ ...
152
+
153
+ >>> print(converter.structure("", str | None))
154
+ None
155
+ ```
156
+
157
+
158
+ ### Lists
159
+
160
+ Lists can be structured from any iterable object.
161
+ Types converting to lists are:
162
+
163
+ - `collections.abc.MutableSequence[T]`
164
+ - `typing.List[T]`
165
+ - `list[T]`
166
+
167
+ In all cases, a new list will be returned, so this operation can be used to copy an iterable into a list.
168
+ A bare type, for example `Sequence` instead of `Sequence[int]`, is equivalent to `Sequence[Any]`.
169
+
170
+ ```{doctest}
171
+
172
+ >>> cattrs.structure((1, 2, 3), MutableSequence[int])
173
+ [1, 2, 3]
174
+ ```
175
+
176
+ When unstructuring, lists are copied and their contents are handled according to their inner type.
177
+ A useful use case for unstructuring collections is to create a deep copy of a complex or recursive collection.
178
+
179
+ ```{versionchanged} 25.2.0
180
+ Sequences are no longer structured into lists by default, but tuples.
181
+ ```
182
+
183
+ ### Dictionaries
184
+
185
+ Dictionaries can be produced from other mapping objects.
186
+ More precisely, the unstructured object must expose an [`items()`](https://docs.python.org/3/library/stdtypes.html#dict.items) method producing an iterable of key-value tuples,
187
+ and be able to be passed to the `dict` constructor as an argument.
188
+ Types converting to dictionaries are:
189
+
190
+ - `dict[K, V]` and `typing.Dict[K, V]`
191
+ - `collections.abc.MutableMapping[K, V]`
192
+ - `collections.abc.Mapping[K, V]`
193
+
194
+ In all cases, a new dict will be returned, so this operation can be used to copy a mapping into a dict.
195
+ Any type parameters set to `typing.Any` will be passed through unconverted.
196
+ If both type parameters are absent, they will be treated as `Any` too.
197
+
198
+ ```{doctest}
199
+
200
+ >>> from collections import OrderedDict
201
+ >>> cattrs.structure(OrderedDict([(1, 2), (3, 4)]), dict)
202
+ {1: 2, 3: 4}
203
+ ```
204
+
205
+ Both keys and values are converted.
206
+
207
+ ```{doctest}
208
+
209
+ >>> cattrs.structure({1: None, 2: 2.0}, dict[str, Optional[int]])
210
+ {'1': None, '2': 2}
211
+ ```
212
+
213
+ ### frozendicts
214
+
215
+ On Python 3.15+, `frozendict` and `frozendict[K, V]` are supported.
216
+ Structuring produces a `frozendict`, converting keys and values according to the
217
+ type arguments when provided.
218
+ {class}`Converter <cattrs.Converter>` unstructures frozen dictionaries into plain
219
+ dictionaries, while {class}`BaseConverter <cattrs.BaseConverter>` preserves the
220
+ `frozendict` type.
221
+ `Mapping` unstructure collection overrides also apply to `frozendict`.
222
+
223
+ ### defaultdicts
224
+
225
+ [`defaultdicts`](https://docs.python.org/3/library/collections.html#collections.defaultdict)
226
+ can be structured by default if they can be initialized using their value type hint.
227
+ Supported types are:
228
+
229
+ - `collections.defaultdict[K, V]`
230
+ - `typing.DefaultDict[K, V]`
231
+
232
+ For example, `defaultdict[str, int]` works since _cattrs_ will initialize it with `defaultdict(int)`.
233
+
234
+ This also means `defaultdicts` without key and value annotations (bare `defaultdicts`) cannot be structured by default.
235
+
236
+ `defaultdicts` with arbitrary default factories can be structured by using {meth}`defaultdict_structure_factory <cattrs.cols.defaultdict_structure_factory>`:
237
+
238
+ ```{doctest}
239
+ >>> from collections import defaultdict
240
+ >>> from cattrs.cols import defaultdict_structure_factory
241
+
242
+ >>> converter = Converter()
243
+ >>> hook = defaultdict_structure_factory(
244
+ ... defaultdict[str, int],
245
+ ... converter,
246
+ ... default_factory=lambda: 1
247
+ ... )
248
+
249
+ >>> hook({"key": 1})
250
+ defaultdict(<function <lambda> at ...>, {'key': 1})
251
+ ```
252
+
253
+ `defaultdicts` are unstructured into plain dictionaries.
254
+
255
+ ```{note}
256
+ `defaultdicts` are not supported by the BaseConverter.
257
+ ```
258
+
259
+ ```{versionadded} 24.2.0
260
+
261
+ ```
262
+
263
+ ### Virtual Subclasses of [`abc.Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping) and [`abc.MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)
264
+
265
+ If a class declares itself a virtual subclass of `collections.abc.Mapping` or `collections.abc.MutableMapping` and its initializer accepts a dictionary,
266
+ _cattrs_ will be able to structure it by default.
267
+
268
+ ### Homogeneous and Heterogeneous Tuples
269
+
270
+ Homogeneous and heterogeneous tuples can be structured from iterable objects.
271
+ Heterogeneous tuples require an iterable with the number of elements matching the number of type parameters exactly.
272
+
273
+ Heterogenous tuples use:
274
+
275
+ - `typing.Tuple[A, B, C, D]`
276
+ - `tuple[A, B, C, D]`
277
+
278
+ Homogeneous tuples use:
279
+
280
+ - `collections.abc.Sequence[T]`
281
+ - `typing.Tuple[T, ...]`
282
+ - `tuple[T, ...]`
283
+
284
+ In all cases a tuple will be produced.
285
+ Any type parameters set to `typing.Any` will be passed through unconverted.
286
+
287
+ ```{doctest}
288
+
289
+ >>> cattrs.structure([1, 2, 3], tuple[int, str, float])
290
+ (1, '2', 3.0)
291
+ ```
292
+
293
+ When unstructuring, heterogeneous tuples unstructure into tuples since it's faster and virtually all serialization libraries support tuples natively.
294
+
295
+ ```{seealso}
296
+ [Support for typing.NamedTuple.](#typingnamedtuple)
297
+ ```
298
+
299
+ ```{note}
300
+ Structuring heterogenous tuples are not supported by the BaseConverter.
301
+ ```
302
+
303
+ ```{versionchanged} 25.2.0
304
+ Sequences are now structured into tuples.
305
+ ```
306
+
307
+ ```{versionchanged} 26.2.0
308
+ The default {class}`Converter <cattrs.Converter>` now generates and caches specialized structuring hooks for heterogeneous tuples, improving repeated structuring performance.
309
+ ```
310
+
311
+ ### Deques
312
+
313
+ Deques can be structured from any iterable object.
314
+ Types converting to deques are:
315
+
316
+ - `typing.Deque[T]`
317
+ - `collections.deque[T]`
318
+
319
+ In all cases, a new **unbounded** deque (`maxlen=None`) will be produced, so this operation can be used to copy an iterable into a deque.
320
+ If you want to convert into bounded `deque`, registering a custom structuring hook is a good approach.
321
+
322
+ ```{doctest}
323
+
324
+ >>> from collections import deque
325
+ >>> cattrs.structure((1, 2, 3), deque[int])
326
+ deque([1, 2, 3])
327
+ ```
328
+
329
+ Deques are unstructured into lists, or into deques when using the {class}`BaseConverter`.
330
+
331
+ ```{versionadded} 23.1.0
332
+
333
+ ```
334
+
335
+
336
+ ### Sets and Frozensets
337
+
338
+ Sets and frozensets can be structured from any iterable object.
339
+ Types converting to sets are:
340
+
341
+ - `collections.abc.MutableSet[T]`
342
+ - `set[T]`
343
+ - `typing.Set[T]` (deprecated since Python 3.9, use `set[T]` instead)
344
+
345
+ Types converting to frozensets are:
346
+
347
+ - `collections.abc.Set[T]`
348
+ - `frozenset[T]`
349
+ - `typing.FrozenSet[T]` (deprecated since Python 3.9, use `frozenset[T]` instead)
350
+
351
+ In all cases, a new set or frozenset will be returned.
352
+ A bare type, for example `MutableSet` instead of `MutableSet[int]`, is equivalent to `MutableSet[Any]`.
353
+
354
+ ```{doctest}
355
+
356
+ >>> cattrs.structure([1, 2, 3, 4], set)
357
+ {1, 2, 3, 4}
358
+ ```
359
+
360
+ Sets and frozensets are unstructured into the matching class.
361
+
362
+ ```{versionchanged} 25.3.0
363
+ Abstract sets are now structured into frozensets instead of sets.
364
+ ```
365
+
366
+ ### Typed Dicts
367
+
368
+ [TypedDicts](https://peps.python.org/pep-0589/) can be structured from mapping objects, usually dictionaries.
369
+
370
+ ```{doctest}
371
+ >>> from typing import TypedDict
372
+
373
+ >>> class MyTypedDict(TypedDict):
374
+ ... a: int
375
+
376
+ >>> cattrs.structure({"a": "1"}, MyTypedDict)
377
+ {'a': 1}
378
+ ```
379
+
380
+ Both [_total_ and _non-total_](https://peps.python.org/pep-0589/#totality) TypedDicts are supported, and inheritance between any combination works.
381
+ Generic TypedDicts work on Python 3.11 and later, since that is the first Python version that supports them in general.
382
+
383
+ [`typing.Required` and `typing.NotRequired`](https://peps.python.org/pep-0655/) are supported.
384
+
385
+ :::{caution}
386
+ If `from __future__ import annotations` is used or if annotations are given as strings, `Required` and `NotRequired` are ignored by cattrs.
387
+ See [note in the Python documentation](https://docs.python.org/3/library/typing.html#typing.TypedDict.__optional_keys__).
388
+ :::
389
+
390
+ [Similar to _attrs_ classes](customizing.md#using-cattrsgen-hook-factories), un/structuring can be customized using {meth}`cattrs.gen.typeddicts.make_dict_structure_fn` and {meth}`cattrs.gen.typeddicts.make_dict_unstructure_fn`.
391
+
392
+ ```{doctest}
393
+ >>> from typing import TypedDict
394
+ >>> from cattrs import Converter
395
+ >>> from cattrs.gen import override
396
+ >>> from cattrs.gen.typeddicts import make_dict_structure_fn
397
+
398
+ >>> class MyTypedDict(TypedDict):
399
+ ... a: int
400
+ ... b: int
401
+
402
+ >>> c = Converter()
403
+ >>> c.register_structure_hook(
404
+ ... MyTypedDict,
405
+ ... make_dict_structure_fn(
406
+ ... MyTypedDict,
407
+ ... c,
408
+ ... a=override(rename="a-with-dash")
409
+ ... )
410
+ ... )
411
+
412
+ >>> c.structure({"a-with-dash": 1, "b": 2}, MyTypedDict)
413
+ {'b': 2, 'a': 1}
414
+ ```
415
+
416
+ TypedDicts unstructure into dictionaries, potentially unchanged (depending on the exact field types and registered hooks).
417
+
418
+ ```{doctest}
419
+ >>> from typing import TypedDict
420
+ >>> from datetime import datetime, timezone
421
+ >>> from cattrs import Converter
422
+
423
+ >>> class MyTypedDict(TypedDict):
424
+ ... a: datetime
425
+
426
+ >>> c = Converter()
427
+ >>> c.register_unstructure_hook(datetime, lambda d: d.timestamp())
428
+
429
+ >>> c.unstructure({"a": datetime(1970, 1, 1, tzinfo=timezone.utc)}, unstructure_as=MyTypedDict)
430
+ {'a': 0.0}
431
+ ```
432
+
433
+ ```{versionadded} 23.1.0
434
+
435
+ ```
436
+
437
+
438
+ ## _attrs_ Classes and Dataclasses
439
+
440
+ _attrs_ classes and dataclasses work out of the box.
441
+ The fields require type annotations (even if static type-checking is not being used), or they will be treated as [](#typingany).
442
+
443
+ When structuring, given a mapping `d` and class `A`, _cattrs_ will instantiate `A` with `d` unpacked.
444
+
445
+ ```{doctest}
446
+
447
+ >>> @define
448
+ ... class A:
449
+ ... a: int
450
+ ... b: int
451
+
452
+ >>> cattrs.structure({'a': 1, 'b': '2'}, A)
453
+ A(a=1, b=2)
454
+ ```
455
+
456
+ Tuples can be structured into classes using {meth}`structure_attrs_fromtuple() <cattrs.structure_attrs_fromtuple>` (`fromtuple` as in the opposite of [`attrs.astuple`](https://www.attrs.org/en/stable/api.html#attrs.astuple) and {meth}`BaseConverter.unstructure_attrs_astuple`).
457
+
458
+ ```{doctest}
459
+
460
+ >>> @define
461
+ ... class A:
462
+ ... a: str
463
+ ... b: int
464
+
465
+ >>> cattrs.structure_attrs_fromtuple(['string', '2'], A)
466
+ A(a='string', b=2)
467
+ ```
468
+
469
+ Loading from tuples can be made the default by creating a new {class}`Converter <cattrs.Converter>` with `unstruct_strat=cattrs.UnstructureStrategy.AS_TUPLE`.
470
+
471
+ ```{doctest}
472
+
473
+ >>> converter = cattrs.Converter(unstruct_strat=cattrs.UnstructureStrategy.AS_TUPLE)
474
+ >>> @define
475
+ ... class A:
476
+ ... a: str
477
+ ... b: int
478
+
479
+ >>> converter.structure(['string', '2'], A)
480
+ A(a='string', b=2)
481
+ ```
482
+
483
+ Structuring from tuples can also be made the default for specific classes only by registering a hook the usual way.
484
+
485
+ ```{doctest}
486
+
487
+ >>> converter = cattrs.Converter()
488
+
489
+ >>> @define
490
+ ... class A:
491
+ ... a: str
492
+ ... b: int
493
+
494
+ >>> converter.register_structure_hook(A, converter.structure_attrs_fromtuple)
495
+ ```
496
+
497
+
498
+ ### Generics
499
+
500
+ Generic _attrs_ classes and dataclasses are fully supported, both using `typing.Generic` and [PEP 695](https://peps.python.org/pep-0695/).
501
+
502
+ ```python
503
+ >>> @define
504
+ ... class A[T]:
505
+ ... a: T
506
+
507
+ >>> cattrs.structure({"a": "1"}, A[int])
508
+ A(a=1)
509
+ ```
510
+
511
+
512
+ ### Using Attribute Types and Converters
513
+
514
+ By default, {meth}`structure() <cattrs.BaseConverter.structure>` will use hooks registered using {meth}`register_structure_hook() <cattrs.BaseConverter.register_structure_hook>`
515
+ to convert values to the attribute type, and proceed to invoking any converters registered on attributes with `field`.
516
+
517
+ ```{doctest}
518
+
519
+ >>> from ipaddress import IPv4Address, ip_address
520
+ >>> converter = cattrs.Converter()
521
+
522
+ # Note: register_structure_hook has not been called, so this will fallback to 'ip_address'
523
+ >>> @define
524
+ ... class A:
525
+ ... a: IPv4Address = field(converter=ip_address)
526
+
527
+ >>> converter.structure({'a': '127.0.0.1'}, A)
528
+ A(a=IPv4Address('127.0.0.1'))
529
+ ```
530
+
531
+ Priority is still given to hooks registered with {meth}`register_structure_hook() <cattrs.BaseConverter.register_structure_hook>`,
532
+ but this priority can be inverted by setting `prefer_attrib_converters` to `True`.
533
+
534
+ ```{doctest}
535
+
536
+ >>> converter = cattrs.Converter(prefer_attrib_converters=True)
537
+
538
+ >>> @define
539
+ ... class A:
540
+ ... a: int = field(converter=lambda v: int(v) + 5)
541
+
542
+ >>> converter.structure({'a': '10'}, A)
543
+ A(a=15)
544
+ ```
545
+
546
+ ```{seealso}
547
+ If an _attrs_ or dataclass class uses inheritance and as such has one or several subclasses, it can be structured automatically to its exact subtype by using the [include subclasses](strategies.md#include-subclasses-strategy) strategy.
548
+ ```
549
+
550
+
551
+ ## Unions
552
+
553
+ Unions of `NoneType` and a single other type (also known as optionals) are supported by a [special case](#optionals).
554
+
555
+
556
+ ### Automatic Disambiguation
557
+
558
+ _cattrs_ includes an opinionated strategy for automatically handling unions of _attrs_ classes; see [](unions.md#default-union-strategy) for details.
559
+
560
+ When unstructuring these kinds of unions, each union member will be unstructured according to the hook for that type.
561
+
562
+
563
+ ### Unions of Simple Types
564
+
565
+ _cattrs_ comes with the [](strategies.md#union-passthrough), which enables converters to structure unions of many primitive types and literals.
566
+ This strategy can be applied to any converter, and is pre-applied to all [preconf](preconf.md) converters according to their underlying protocols.
567
+
568
+
569
+ ## Special Typing Forms
570
+
571
+
572
+ ### `typing.Any`
573
+
574
+ When structuring, use `typing.Any` to avoid applying any conversions to the object you're structuring; it will simply be passed through.
575
+
576
+ ```{doctest}
577
+
578
+ >>> cattrs.structure(1, Any)
579
+ 1
580
+ >>> d = {1: 1}
581
+ >>> cattrs.structure(d, Any) is d
582
+ True
583
+ ```
584
+
585
+ When unstructuring, `typing.Any` will make the value be unstructured according to its runtime class.
586
+
587
+ ```{versionchanged} 24.1.0
588
+ Previously, the unstructuring rules for `Any` were underspecified, leading to inconsistent behavior.
589
+ ```
590
+
591
+ ```{versionchanged} 24.1.0
592
+ `typing_extensions.Any` is now also supported.
593
+ ```
594
+
595
+ ### `typing.Literal`
596
+
597
+ When structuring, [PEP 586](https://peps.python.org/pep-0586/) literals are validated to be in the allowed set of values.
598
+
599
+ ```{doctest}
600
+ >>> from typing import Literal
601
+
602
+ >>> cattrs.structure(1, Literal[1, 2])
603
+ 1
604
+ ```
605
+
606
+ When unstructuring, literals are passed through.
607
+
608
+ ```{versionadded} 1.7.0
609
+
610
+ ```
611
+
612
+ ### `typing.NamedTuple`
613
+
614
+ Named tuples with type hints (created from [`typing.NamedTuple`](https://docs.python.org/3/library/typing.html#typing.NamedTuple)) are supported.
615
+ Named tuples are un/structured using tuples or lists by default.
616
+
617
+ The {mod}`cattrs.cols` module contains hook factories for un/structuring named tuples using dictionaries instead,
618
+ [see here for details](customizing.md#customizing-named-tuples).
619
+
620
+ ```{versionadded} 24.1.0
621
+
622
+ ```
623
+
624
+ ### `typing.Final`
625
+
626
+ [PEP 591](https://peps.python.org/pep-0591/) Final attribute types (`Final[int]`) are supported and handled according to the inner type (in this case, `int`).
627
+
628
+ ```{versionadded} 23.1.0
629
+
630
+ ```
631
+
632
+
633
+ ### `typing.Annotated`
634
+
635
+ [PEP 593](https://www.python.org/dev/peps/pep-0593/) annotations (`typing.Annotated[type, ...]`) are supported and are handled using the first type present in the annotated type.
636
+
637
+ Additionally, `typing.Annotated` types containing `cattrs.override()` are recognized and used by the _attrs_, dataclass, TypedDict and dict NamedTuple hook factories.
638
+
639
+ ```{versionchanged} 26.1.0
640
+ `Annotated[T, override()]` is now used by the _attrs_, dataclass, TypedDict and dict NamedTuple hook factories.
641
+ ```
642
+
643
+ ```{versionadded} 1.4.0
644
+
645
+ ```
646
+
647
+
648
+ ### Type Aliases
649
+
650
+ [Type aliases](https://docs.python.org/3/library/typing.html#type-aliases) are supported on Python 3.12+ and are handled according to the rules for their underlying type.
651
+ Their hooks can also be overriden using [](customizing.md#predicate-hooks).
652
+
653
+ ```{warning}
654
+ Type aliases using [`typing.TypeAlias`](https://docs.python.org/3/library/typing.html#typing.TypeAlias) aren't supported since there is no way at runtime to distinguish them from their underlying types.
655
+ ```
656
+
657
+ ```{versionchanged} 26.2.0
658
+ The [union passthrough strategy](strategies.md#union-passthrough) also recognizes type aliases used as union members.
659
+ ```
660
+
661
+ ```python
662
+ >>> from datetime import datetime, UTC
663
+
664
+ >>> type IsoDate = datetime
665
+
666
+ >>> converter = cattrs.Converter()
667
+ >>> converter.register_structure_hook_func(
668
+ ... lambda t: t is IsoDate, lambda v, _: datetime.fromisoformat(v)
669
+ ... )
670
+ >>> converter.register_unstructure_hook_func(
671
+ ... lambda t: t is IsoDate, lambda v: v.isoformat()
672
+ ... )
673
+
674
+ >>> converter.structure("2022-01-01", IsoDate)
675
+ datetime.datetime(2022, 1, 1, 0, 0)
676
+ >>> converter.unstructure(datetime.now(UTC), unstructure_as=IsoDate)
677
+ '2023-11-20T23:10:46.728394+00:00'
678
+ ```
679
+
680
+ ```{versionadded} 24.1.0
681
+
682
+ ```
683
+
684
+
685
+ ### `typing.NewType`
686
+
687
+ [NewTypes](https://docs.python.org/3/library/typing.html#newtype) are supported and are handled according to the rules for their underlying type.
688
+ Their hooks can also be overriden using {meth}`Converter.register_structure_hook() <cattrs.BaseConverter.register_structure_hook>`.
689
+
690
+ ```{doctest}
691
+
692
+ >>> from typing import NewType
693
+ >>> from datetime import datetime
694
+
695
+ >>> IsoDate = NewType("IsoDate", datetime)
696
+
697
+ >>> converter = cattrs.Converter()
698
+ >>> converter.register_structure_hook(IsoDate, lambda v, _: datetime.fromisoformat(v))
699
+
700
+ >>> converter.structure("2022-01-01", IsoDate)
701
+ datetime.datetime(2022, 1, 1, 0, 0)
702
+ ```
703
+
704
+ ```{versionadded} 22.2.0
705
+
706
+ ```
707
+
708
+
709
+ ### `typing.Protocol`
710
+
711
+ [Protocols](https://peps.python.org/pep-0544/) cannot be structured by default and so require custom hooks.
712
+
713
+ Protocols are unstructured according to the actual runtime type of the value.
714
+
715
+ ```{versionadded} 1.9.0
716
+
717
+ ```
718
+
719
+ ### `typing.Self`
720
+
721
+ Attributes annotated using [the Self type](https://docs.python.org/3/library/typing.html#typing.Self) are supported in _attrs_ classes, dataclasses, TypedDicts and NamedTuples
722
+ (when using [the dict un/structure factories](customizing.md#customizing-named-tuples)).
723
+
724
+ ```{doctest}
725
+ >>> from typing import Self
726
+
727
+ >>> @define
728
+ ... class LinkedListNode:
729
+ ... element: int
730
+ ... next: Self | None = None
731
+
732
+ >>> cattrs.unstructure(LinkedListNode(1, LinkedListNode(2, None)))
733
+ {'element': 1, 'next': {'element': 2, 'next': None}}
734
+ >>> cattrs.structure({'element': 1, 'next': {'element': 2, 'next': None}}, LinkedListNode)
735
+ LinkedListNode(element=1, next=LinkedListNode(element=2, next=None))
736
+ ```
737
+
738
+ ```{note}
739
+ Attributes annotated with `typing.Self` are not supported by the BaseConverter, as this is too complex for it.
740
+ ```
741
+
742
+ ```{versionadded} 25.1.0
743
+
744
+ ```
tasks/tasksmith-c756db832cf4/tests/source/docs/history.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ```{include} ../HISTORY.md
2
+
3
+ ```
tasks/tasksmith-c756db832cf4/tests/source/docs/indepth.md ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Converters In-Depth
2
+ ```{currentmodule} cattrs
3
+ ```
4
+
5
+ Converters are registries of rules _cattrs_ uses to perform function composition and generate its un/structuring functions.
6
+
7
+ Currently, a converter contains the following state:
8
+
9
+ - a registry of unstructure hooks, backed by a [singledispatch](https://docs.python.org/3/library/functools.html#functools.singledispatch) and a {class}`FunctionDispatch <cattrs.dispatch.FunctionDispatch>`, wrapped in a [cache](https://docs.python.org/3/library/functools.html#functools.cache).
10
+ - a registry of structure hooks, backed by a different singledispatch and `FunctionDispatch`, and a different cache.
11
+ - a `detailed_validation` flag (defaulting to true), determining whether the converter uses [detailed validation](validation.md#detailed-validation).
12
+ - a reference to {class}`an unstructuring strategy <cattrs.UnstructureStrategy>` (either AS_DICT or AS_TUPLE).
13
+ - a `prefer_attrib_converters` flag (defaulting to false), determining whether to favor _attrs_ converters over normal _cattrs_ machinery when structuring _attrs_ classes
14
+ - a `dict_factory` callable, a legacy parameter used for creating `dicts` when dumping _attrs_ classes using `AS_DICT`.
15
+
16
+ Converters may be cloned using the {meth}`Converter.copy() <cattrs.BaseConverter.copy>` method.
17
+ The new copy may be changed through the `copy` arguments, but will retain all manually registered hooks from the original.
18
+
19
+
20
+ ## Customizing Collection Unstructuring
21
+
22
+ ```{tip}
23
+ See [](customizing.md#customizing-collections) for a more modern and more powerful way of customizing collection handling.
24
+ ```
25
+
26
+ Overriding collection unstructuring in a generic way can be a very useful feature.
27
+ A common example is using a JSON library that doesn't support sets, but expects lists and tuples instead.
28
+
29
+ Using ordinary unstructuring hooks for this is unwieldy due to the semantics of
30
+ [singledispatch](https://docs.python.org/3/library/functools.html#functools.singledispatch);
31
+ in other words, you'd need to register hooks for all specific types of set you're using (`set[int]`, `set[float]`,
32
+ `set[str]`...), which is not useful.
33
+
34
+ Function-based hooks can be used instead, but come with their own set of challenges - they're complicated to write efficiently.
35
+
36
+ The {class}`Converter` supports easy customizations of collection unstructuring using its `unstruct_collection_overrides` parameter.
37
+ For example, to unstructure all sets into lists, use the following:
38
+
39
+ ```{doctest}
40
+
41
+ >>> from collections.abc import Set
42
+ >>> converter = cattrs.Converter(unstruct_collection_overrides={Set: list})
43
+
44
+ >>> converter.unstructure({1, 2, 3})
45
+ [1, 2, 3]
46
+ ```
47
+
48
+ Going even further, the `Converter` contains heuristics to support the following Python types, in order of decreasing generality:
49
+
50
+ - `typing.Sequence`, `typing.MutableSequence`, `list`, `deque`, `tuple`
51
+ - `typing.Set`, `frozenset`, `typing.MutableSet`, `set`
52
+ - `typing.Mapping`, `typing.MutableMapping`, `dict`, `defaultdict`, `collections.OrderedDict`, `collections.Counter`
53
+
54
+ For example, if you override the unstructure type for `Sequence`, but not for `MutableSequence`, `list` or `tuple`, the override will also affect those types.
55
+ An easy way to remember the rule:
56
+
57
+ - all `MutableSequence` s are `Sequence` s, so the override will apply
58
+ - all `list` s are `MutableSequence` s, so the override will apply
59
+ - all `tuple` s are `Sequence` s, so the override will apply
60
+
61
+ If, however, you override only `MutableSequence`, fields annotated as `Sequence` will not be affected (since not all sequences are mutable sequences), and fields annotated as tuples will not be affected (since tuples
62
+ are not mutable sequences in the first place).
63
+
64
+ Similar logic applies to the set and mapping hierarchies.
65
+
66
+ Make sure you're using the types from `collections.abc` on Python 3.9+, and from `typing` on older Python versions.
67
+
68
+
69
+ ## Fallback Hook Factories
70
+
71
+ By default, when a {class}`converter <cattrs.BaseConverter>` cannot handle a type it will:
72
+
73
+ * when unstructuring, pass the value through unchanged
74
+ * when structuring, raise a {class}`cattrs.errors.StructureHandlerNotFoundError` asking the user to add configuration
75
+
76
+ These behaviors can be customized by providing custom [hook factories](usage.md#using-factory-hooks) when creating the converter.
77
+
78
+ ```python
79
+ >>> from pickle import dumps
80
+
81
+ >>> class Unsupported:
82
+ ... """An artisinal (non-attrs) class, unsupported by default."""
83
+
84
+ >>> converter = Converter(unstructure_fallback_factory=lambda _: dumps)
85
+ >>> instance = Unsupported()
86
+ >>> converter.unstructure(instance)
87
+ b'\x80\x04\x95\x18\x00\x00\x00\x00\x00\x00\x00\x8c\x08__main__\x94\x8c\x04Test\x94\x93\x94)\x81\x94.'
88
+ ```
89
+
90
+ This also enables converters to be chained.
91
+
92
+ ```python
93
+ >>> parent = Converter()
94
+
95
+ >>> child = Converter(
96
+ ... unstructure_fallback_factory=parent.get_unstructure_hook,
97
+ ... structure_fallback_factory=parent.get_structure_hook,
98
+ ... )
99
+ ```
100
+
101
+ ```{versionadded} 23.2.0
102
+
103
+ ```
104
+
105
+ ## `cattrs.Converter`
106
+
107
+ The {class}`Converter` is a converter variant that automatically generates, compiles and caches specialized structuring and unstructuring hooks for _attrs_ classes, dataclasses and TypedDicts.
108
+
109
+ `Converter` differs from the {class}`cattrs.BaseConverter` in the following ways:
110
+
111
+ - structuring and unstructuring of _attrs_ classes is slower the first time, but faster every subsequent time
112
+ - structuring and unstructuring can be customized
113
+ - support for _attrs_ classes with PEP563 (postponed) annotations
114
+ - support for generic _attrs_ classes
115
+ - support for easy overriding collection unstructuring
116
+
117
+ The {class}`Converter` used to be called `GenConverter`, and that alias is still present for backwards compatibility.
118
+
119
+ ## `cattrs.BaseConverter`
120
+
121
+ The {class}`BaseConverter` is a simpler and slower converter variant.
122
+ It does no code generation, so it may be faster on first-use which can be useful in specific cases, like CLI applications where startup time is more important than throughput.
tasks/tasksmith-c756db832cf4/tests/source/docs/index.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # *cattrs*: Flexible Object Serialization and Validation
2
+
3
+ *Because validation belongs to the edges.*
4
+
5
+ ---
6
+
7
+ ```{include} ../README.md
8
+ :start-after: "begin-teaser -->"
9
+ :end-before: "<!-- end-teaser"
10
+ ```
11
+
12
+ ```{include} ../README.md
13
+ :start-after: "begin-example -->"
14
+ :end-before: "<!-- end-example"
15
+ ```
16
+
17
+ ---
18
+
19
+ However, *cattrs* does **much** more with a focus on **functional composition** and **not coupling** your data model to its serialization and validation rules.
20
+
21
+ To learn more on why to use *cattrs*, have a look at {doc}`why`, and if you're convinced jump right into {doc}`basics`!
22
+
23
+
24
+ ```{toctree}
25
+ ---
26
+ maxdepth: 2
27
+ hidden: true
28
+ caption: Introduction
29
+ ---
30
+
31
+ why
32
+ basics
33
+ defaulthooks
34
+ ```
35
+
36
+ ```{toctree}
37
+ ---
38
+ maxdepth: 2
39
+ hidden: true
40
+ caption: User Guide
41
+ ---
42
+
43
+ customizing
44
+ strategies
45
+ recipes
46
+ validation
47
+ preconf
48
+ unions
49
+ usage
50
+ migrations
51
+ indepth
52
+ ```
53
+
54
+ ```{toctree}
55
+ ---
56
+ maxdepth: 2
57
+ hidden: true
58
+ caption: Reference
59
+ ---
60
+
61
+ API <modules>
62
+ modindex
63
+ genindex
64
+ ```
65
+
66
+ ```{toctree}
67
+ ---
68
+ maxdepth: 2
69
+ hidden: true
70
+ caption: Dev Guide
71
+ ---
72
+
73
+ contributing
74
+ benchmarking
75
+ ```
76
+
77
+ ```{toctree}
78
+ ---
79
+ caption: Meta
80
+ hidden: true
81
+ maxdepth: 1
82
+ ---
83
+
84
+ history
85
+ PyPI <https://pypi.org/project/cattrs/>
86
+ GitHub <https://github.com/python-attrs/cattrs>
87
+ ```
tasks/tasksmith-c756db832cf4/tests/source/docs/make.bat ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @ECHO OFF
2
+
3
+ REM Command file for Sphinx documentation
4
+
5
+ if "%SPHINXBUILD%" == "" (
6
+ set SPHINXBUILD=sphinx-build
7
+ )
8
+ set BUILDDIR=_build
9
+ set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
10
+ set I18NSPHINXOPTS=%SPHINXOPTS% .
11
+ if NOT "%PAPER%" == "" (
12
+ set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
13
+ set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
14
+ )
15
+
16
+ if "%1" == "" goto help
17
+
18
+ if "%1" == "help" (
19
+ :help
20
+ echo.Please use `make ^<target^>` where ^<target^> is one of
21
+ echo. html to make standalone HTML files
22
+ echo. dirhtml to make HTML files named index.html in directories
23
+ echo. singlehtml to make a single large HTML file
24
+ echo. pickle to make pickle files
25
+ echo. json to make JSON files
26
+ echo. htmlhelp to make HTML files and a HTML help project
27
+ echo. qthelp to make HTML files and a qthelp project
28
+ echo. devhelp to make HTML files and a Devhelp project
29
+ echo. epub to make an epub
30
+ echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
31
+ echo. text to make text files
32
+ echo. man to make manual pages
33
+ echo. texinfo to make Texinfo files
34
+ echo. gettext to make PO message catalogs
35
+ echo. changes to make an overview over all changed/added/deprecated items
36
+ echo. xml to make Docutils-native XML files
37
+ echo. pseudoxml to make pseudoxml-XML files for display purposes
38
+ echo. linkcheck to check all external links for integrity
39
+ echo. doctest to run all doctests embedded in the documentation if enabled
40
+ goto end
41
+ )
42
+
43
+ if "%1" == "clean" (
44
+ for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
45
+ del /q /s %BUILDDIR%\*
46
+ goto end
47
+ )
48
+
49
+
50
+ %SPHINXBUILD% 2> nul
51
+ if errorlevel 9009 (
52
+ echo.
53
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
54
+ echo.installed, then set the SPHINXBUILD environment variable to point
55
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
56
+ echo.may add the Sphinx directory to PATH.
57
+ echo.
58
+ echo.If you don't have Sphinx installed, grab it from
59
+ echo.http://sphinx-doc.org/
60
+ exit /b 1
61
+ )
62
+
63
+ if "%1" == "html" (
64
+ %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
65
+ if errorlevel 1 exit /b 1
66
+ echo.
67
+ echo.Build finished. The HTML pages are in %BUILDDIR%/html.
68
+ goto end
69
+ )
70
+
71
+ if "%1" == "dirhtml" (
72
+ %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
73
+ if errorlevel 1 exit /b 1
74
+ echo.
75
+ echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
76
+ goto end
77
+ )
78
+
79
+ if "%1" == "singlehtml" (
80
+ %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
81
+ if errorlevel 1 exit /b 1
82
+ echo.
83
+ echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
84
+ goto end
85
+ )
86
+
87
+ if "%1" == "pickle" (
88
+ %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
89
+ if errorlevel 1 exit /b 1
90
+ echo.
91
+ echo.Build finished; now you can process the pickle files.
92
+ goto end
93
+ )
94
+
95
+ if "%1" == "json" (
96
+ %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
97
+ if errorlevel 1 exit /b 1
98
+ echo.
99
+ echo.Build finished; now you can process the JSON files.
100
+ goto end
101
+ )
102
+
103
+ if "%1" == "htmlhelp" (
104
+ %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
105
+ if errorlevel 1 exit /b 1
106
+ echo.
107
+ echo.Build finished; now you can run HTML Help Workshop with the ^
108
+ .hhp project file in %BUILDDIR%/htmlhelp.
109
+ goto end
110
+ )
111
+
112
+ if "%1" == "qthelp" (
113
+ %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
114
+ if errorlevel 1 exit /b 1
115
+ echo.
116
+ echo.Build finished; now you can run "qcollectiongenerator" with the ^
117
+ .qhcp project file in %BUILDDIR%/qthelp, like this:
118
+ echo.^> qcollectiongenerator %BUILDDIR%\qthelp\cattrs.qhcp
119
+ echo.To view the help file:
120
+ echo.^> assistant -collectionFile %BUILDDIR%\qthelp\cattrs.ghc
121
+ goto end
122
+ )
123
+
124
+ if "%1" == "devhelp" (
125
+ %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
126
+ if errorlevel 1 exit /b 1
127
+ echo.
128
+ echo.Build finished.
129
+ goto end
130
+ )
131
+
132
+ if "%1" == "epub" (
133
+ %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
134
+ if errorlevel 1 exit /b 1
135
+ echo.
136
+ echo.Build finished. The epub file is in %BUILDDIR%/epub.
137
+ goto end
138
+ )
139
+
140
+ if "%1" == "latex" (
141
+ %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
142
+ if errorlevel 1 exit /b 1
143
+ echo.
144
+ echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
145
+ goto end
146
+ )
147
+
148
+ if "%1" == "latexpdf" (
149
+ %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
150
+ cd %BUILDDIR%/latex
151
+ make all-pdf
152
+ cd %BUILDDIR%/..
153
+ echo.
154
+ echo.Build finished; the PDF files are in %BUILDDIR%/latex.
155
+ goto end
156
+ )
157
+
158
+ if "%1" == "latexpdfja" (
159
+ %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
160
+ cd %BUILDDIR%/latex
161
+ make all-pdf-ja
162
+ cd %BUILDDIR%/..
163
+ echo.
164
+ echo.Build finished; the PDF files are in %BUILDDIR%/latex.
165
+ goto end
166
+ )
167
+
168
+ if "%1" == "text" (
169
+ %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
170
+ if errorlevel 1 exit /b 1
171
+ echo.
172
+ echo.Build finished. The text files are in %BUILDDIR%/text.
173
+ goto end
174
+ )
175
+
176
+ if "%1" == "man" (
177
+ %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
178
+ if errorlevel 1 exit /b 1
179
+ echo.
180
+ echo.Build finished. The manual pages are in %BUILDDIR%/man.
181
+ goto end
182
+ )
183
+
184
+ if "%1" == "texinfo" (
185
+ %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
186
+ if errorlevel 1 exit /b 1
187
+ echo.
188
+ echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
189
+ goto end
190
+ )
191
+
192
+ if "%1" == "gettext" (
193
+ %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
194
+ if errorlevel 1 exit /b 1
195
+ echo.
196
+ echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
197
+ goto end
198
+ )
199
+
200
+ if "%1" == "changes" (
201
+ %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
202
+ if errorlevel 1 exit /b 1
203
+ echo.
204
+ echo.The overview file is in %BUILDDIR%/changes.
205
+ goto end
206
+ )
207
+
208
+ if "%1" == "linkcheck" (
209
+ %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
210
+ if errorlevel 1 exit /b 1
211
+ echo.
212
+ echo.Link check complete; look for any errors in the above output ^
213
+ or in %BUILDDIR%/linkcheck/output.txt.
214
+ goto end
215
+ )
216
+
217
+ if "%1" == "doctest" (
218
+ %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
219
+ if errorlevel 1 exit /b 1
220
+ echo.
221
+ echo.Testing of doctests in the sources finished, look at the ^
222
+ results in %BUILDDIR%/doctest/output.txt.
223
+ goto end
224
+ )
225
+
226
+ if "%1" == "xml" (
227
+ %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
228
+ if errorlevel 1 exit /b 1
229
+ echo.
230
+ echo.Build finished. The XML files are in %BUILDDIR%/xml.
231
+ goto end
232
+ )
233
+
234
+ if "%1" == "pseudoxml" (
235
+ %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
236
+ if errorlevel 1 exit /b 1
237
+ echo.
238
+ echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
239
+ goto end
240
+ )
241
+
242
+ if "%1" == "apidoc" (
243
+ sphinx-apidoc -o . ../src/cattrs/ -f
244
+ if errorlevel 1 exit /b 1
245
+ echo.
246
+ goto end
247
+ )
248
+
249
+ :end
tasks/tasksmith-c756db832cf4/tests/source/docs/migrations.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Migrations
2
+
3
+ ```{currentmodule} cattrs
4
+ ```
5
+
6
+ _cattrs_ sometimes changes in backwards-incompatible ways.
7
+ This page contains guidance for changes and workarounds for restoring legacy behavior.
8
+
9
+ ## 26.2.0
10
+
11
+ ### Naive datetimes unstructuring as UTC in the _msgpack_ and _cbor2_ converters
12
+
13
+ The _msgpack_ and _cbor2_ converters unstructure `datetime` s into UNIX timestamps using `datetime.timestamp`, which reads a naive `datetime` as local time.
14
+ The serialized value therefore depended on the timezone of the machine doing the unstructuring, while the structure hooks read timestamps back as UTC.
15
+ From this version on, naive `datetime` s are assumed to be UTC when unstructuring, so both ends of the round-trip agree and the payload no longer depends on the host.
16
+
17
+ Aware `datetime` s are unaffected.
18
+
19
+ The old behavior can be restored by registering `datetime.timestamp` directly on a converter.
20
+
21
+ ```python
22
+ >>> from datetime import datetime
23
+
24
+ >>> converter.register_unstructure_hook(datetime, datetime.timestamp)
25
+ ```
26
+
27
+ ## 25.3.0
28
+
29
+ ### Abstract sets structuring into frozensets
30
+
31
+ From this version on, abstract sets (`collection.abc.Set`) structure into frozensets.
32
+
33
+ The old behavior can be restored by registering the {meth}`BaseConverter._structure_set <cattrs.BaseConverter._structure_set>` method using the {meth}`is_abstract_set <cattrs.cols.is_abstract_set>` predicate on a converter.
34
+
35
+ ```python
36
+ >>> from cattrs.cols import is_abstract_set
37
+
38
+ >>> converter.register_structure_hook_func(is_abstract_set, converter._structure_set)
39
+ ```
40
+
41
+ ## 25.2.0
42
+
43
+ ### Sequences structuring into tuples
44
+
45
+ Sequences were changed to structure into tuples instead of lists.
46
+
47
+ The old behavior can be restored by registering the `list_structure_factory` using the `is_sequence` predicate on a converter.
48
+
49
+ ```python
50
+ >>> from cattrs.cols import is_sequence, list_structure_factory
51
+
52
+ >>> converter.register_structure_hook_factory(is_sequence, list_structure_factory)
53
+ ```
54
+
55
+ ## 25.1.0
56
+
57
+ ### The default structure hook fallback factory
58
+
59
+ The default structure hook fallback factory was changed to more eagerly raise errors for missing hooks.
60
+
61
+ The old behavior can be restored by explicitly passing in the old hook fallback factory when instantiating the converter.
62
+
63
+
64
+ ```python
65
+ >>> from cattrs.fns import raise_error
66
+
67
+ >>> c = Converter(structure_fallback_factory=lambda _: raise_error)
68
+ # Or
69
+ >>> c = BaseConverter(structure_fallback_factory=lambda _: raise_error)
70
+ ```
71
+
72
+ ### `cattrs.gen.MappingStructureFn` and `cattrs.gen.DictStructureFn` removal
73
+
74
+ The internal `cattrs.gen.MappingStructureFn` and `cattrs.gen.DictStructureFn` types were replaced by a more general type, `cattrs.SimpleStructureHook[In, T]`.
75
+ If you were using `MappingStructureFn`, use `SimpleStructureHook[Mapping[Any, Any], T]` instead.
76
+ If you were using `DictStructureFn`, use `SimpleStructureHook[Mapping[str, Any], T]` instead.
tasks/tasksmith-c756db832cf4/tests/source/docs/modules.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ cattrs
2
+ ======
3
+
4
+ .. toctree::
5
+ :maxdepth: 4
6
+
7
+ cattrs
tasks/tasksmith-c756db832cf4/tests/source/docs/preconf.md ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Preconfigured Converters
2
+
3
+ The {mod}`cattrs.preconf` package contains factories for preconfigured converters, specifically adjusted for particular serialization libraries.
4
+
5
+ For example, to get a converter configured for _orjson_:
6
+
7
+ ```{doctest}
8
+
9
+ >>> from cattrs.preconf.orjson import make_converter
10
+
11
+ >>> converter = make_converter() # Takes the same parameters as the `cattrs.Converter`
12
+ ```
13
+
14
+ Converters obtained this way can be customized further, just like any other converter.
15
+
16
+ For compatibility and performance reasons, these converters are usually configured to unstructure differently than ordinary `Converters`.
17
+ A couple of examples:
18
+ * the {class}`_orjson_ converter <cattrs.preconf.orjson.OrjsonConverter>` is configured to pass `datetime` instances unstructured since _orjson_ can handle them faster.
19
+ * the {class}`_msgspec_ JSON converter <cattrs.preconf.msgspec.MsgspecJsonConverter>` is configured to pass through some dataclasses and _attrs_classes,
20
+ if the output is identical to what normal unstructuring would have produced, since _msgspec_ can handle them faster.
21
+
22
+ The intended usage is to pass the unstructured output directly to the underlying library,
23
+ or use `converter.dumps` which will do it for you.
24
+
25
+ These converters support all [default hooks](defaulthooks.md)
26
+ and the following additional classes and type annotations,
27
+ both for structuring and unstructuring:
28
+
29
+ - `datetime.datetime`, `datetime.date`
30
+
31
+ ```{versionadded} 22.1.0
32
+ All preconf converters now have `loads` and `dumps` methods, which combine un/structuring and the de/serialization logic from their underlying libraries.
33
+ ```
34
+
35
+ ```{doctest}
36
+
37
+ >>> from cattrs.preconf.json import make_converter
38
+
39
+ >>> converter = make_converter()
40
+
41
+ >>> @define
42
+ ... class Test:
43
+ ... a: int
44
+
45
+ >>> converter.dumps(Test(1))
46
+ '{"a": 1}'
47
+ ```
48
+
49
+ Particular libraries may have additional constraints documented below.
50
+
51
+ Third-party libraries can be specified as optional (extra) dependencies on _cattrs_ during installation.
52
+ Optional install targets should match the name of the {mod}`cattrs.preconf` modules.
53
+
54
+ ```console
55
+ # Using pip
56
+ $ pip install cattrs[ujson]
57
+
58
+ # Usinv uv
59
+ $ uv add cattrs[msgspec]
60
+
61
+ # Using pdm
62
+ $ pdm add cattrs[orjson]
63
+
64
+ # Using poetry
65
+ $ poetry add --extras tomlkit cattrs
66
+ ```
67
+
68
+
69
+ ## Standard Library _json_
70
+
71
+ Found at {mod}`cattrs.preconf.json`.
72
+
73
+ Bytes are serialized as base 85 strings. Counters are serialized as dictionaries. Sets are serialized as lists, and deserialized back into sets. `datetime` s and `date` s are serialized as ISO 8601 strings.
74
+
75
+
76
+ ## _orjson_
77
+
78
+ Found at {mod}`cattrs.preconf.orjson`.
79
+
80
+ Bytes are un/structured as base 85 strings.
81
+ Sets are unstructured into lists, and structured back into sets.
82
+ `datetime` s and `date` s are passed through to be unstructured into RFC 3339 by _orjson_ itself.
83
+ Typed named tuples are unstructured into ordinary tuples, and then into JSON arrays by _orjson_.
84
+
85
+ _orjson_ doesn't support integers less than -9223372036854775808, and greater than 9223372036854775807.
86
+ _orjson_ only supports mappings with string keys so mappings will have their keys stringified before serialization, and destringified during deserialization.
87
+
88
+
89
+ ## _msgspec_
90
+
91
+ Found at {mod}`cattrs.preconf.msgspec`.
92
+ Only JSON functionality is currently available, other formats supported by msgspec to follow in the future.
93
+
94
+ [_msgspec_ structs](https://jcristharif.com/msgspec/structs.html) are supported, but not composable - a struct will be handed over to _msgspec_ directly, and _msgspec_ will handle and all of its fields, recursively.
95
+ _cattrs_ may get more sophisticated handling of structs in the future.
96
+
97
+ [_msgspec_ strict mode](https://jcristharif.com/msgspec/usage.html#strict-vs-lax-mode) is used by default.
98
+ This can be customized by changing the {meth}`encoder <cattrs.preconf.msgspec.MsgspecJsonConverter.encoder>` attribute on the converter.
99
+
100
+ What _cattrs_ calls _unstructuring_ and _structuring_, _msgspec_ calls [`to_builtins` and `convert`](https://jcristharif.com/msgspec/converters.html).
101
+ What _cattrs_ refers to as _dumping_ and _loading_, _msgspec_ refers to as [`encoding` and `decoding`](https://jcristharif.com/msgspec/usage.html).
102
+
103
+ Compatibility notes:
104
+ - Bytes are un/structured as base 64 strings directly by _msgspec_ itself.
105
+ - _msgspec_ [encodes special float values](https://jcristharif.com/msgspec/supported-types.html#float) (`NaN, Inf, -Inf`) as `null`.
106
+ - `datetime` s and `date` s are passed through to be unstructured into RFC 3339 by _msgspec_ itself.
107
+ - _attrs_ classes, dataclasses and sequences are handled directly by _msgspec_ if possible, otherwise by the normal _cattrs_ machinery.
108
+ This means it's possible the validation errors produced may be _msgspec_ validation errors instead of _cattrs_ validation errors.
109
+
110
+ This converter supports {meth}`get_loads_hook() <cattrs.preconf.msgspec.MsgspecJsonConverter.get_loads_hook>` and {meth}`get_dumps_hook() <cattrs.preconf.msgspec.MsgspecJsonConverter.get_dumps_hook>`.
111
+ These are factories for dumping and loading functions (as opposed to unstructuring and structuring); the hooks returned by this may be further optimized to offload as much work as possible to _msgspec_.
112
+
113
+ ```python
114
+ >>> from cattrs.preconf.msgspec import make_converter
115
+
116
+ >>> @define
117
+ ... class Test:
118
+ ... a: int
119
+
120
+ >>> converter = make_converter()
121
+ >>> dumps = converter.get_dumps_hook(A)
122
+
123
+ >>> dumps(Test(1)) # Will use msgspec directly.
124
+ b'{"a":1}'
125
+ ```
126
+
127
+ Due to its complexity, this converter is currently _provisional_ and may slightly change as the best integration patterns are discovered.
128
+
129
+ _msgspec_ doesn't support PyPy.
130
+
131
+ ```{versionadded} 24.1.0
132
+
133
+ ```
134
+
135
+
136
+ ## _tomllib_
137
+
138
+ Found at {mod}`cattrs.preconf.tomllib`.
139
+
140
+ Bytes are serialized as base 85 strings. Sets are serialized as lists, and deserialized back into sets.
141
+ Tuples are serialized as lists, and deserialized back into tuples.
142
+ _tomllib_ only supports mappings with string keys so mappings will have their keys stringified before serialization, and destringified during deserialization.
143
+
144
+ Writing is supported via the [_tomli-w_](https://pypi.org/project/tomli-w/) library; this needs to be installed separately (or depend on the `cattrs[tomllib]` extra).
145
+
146
+ On Python 3.10, the [_tomli_](https://pypi.org/project/tomli/) library is required.
147
+
148
+ ```{versionadded} 26.1.0
149
+
150
+ ```
151
+
152
+
153
+ ## _ujson_
154
+
155
+ Found at {mod}`cattrs.preconf.ujson`.
156
+
157
+ Bytes are serialized as base 85 strings. Sets are serialized as lists, and deserialized back into sets. `datetime` s and `date` s are serialized as ISO 8601 strings.
158
+
159
+ _ujson_ doesn't support integers less than -9223372036854775808, and greater than 9223372036854775807, nor does it support `float('inf')`.
160
+
161
+
162
+ ## _msgpack_
163
+
164
+ Found at {mod}`cattrs.preconf.msgpack`.
165
+
166
+ Sets are serialized as lists, and deserialized back into sets. `datetime` s are serialized as UNIX timestamp float values. `date` s are serialized as midnight-aligned UNIX timestamp float values.
167
+ Naive `datetime` s are assumed to be UTC, which is also how timestamps are interpreted when structuring.
168
+
169
+ ```{versionchanged} 26.2.0
170
+ Naive `datetime` s are assumed to be UTC when unstructuring.
171
+ They were previously interpreted as local time, making the serialized value depend on the timezone of the machine doing the unstructuring.
172
+ ```
173
+
174
+ _msgpack_ doesn't support integers less than -9223372036854775808, and greater than 18446744073709551615.
175
+
176
+ When parsing msgpack data from bytes, the library needs to be passed `strict_map_key=False` to get the full range of compatibility.
177
+
178
+
179
+ ## _cbor2_
180
+
181
+ Found at {mod}`cattrs.preconf.cbor2`.
182
+
183
+ _cbor2_ implements a fully featured CBOR encoder with several extensions for handling shared references, big integers, rational numbers and so on.
184
+
185
+ Sets are serialized and deserialized to sets.
186
+ Tuples are serialized as lists.
187
+
188
+ `datetime` s are serialized as a text string by default (CBOR Tag 0).
189
+ Use keyword argument `datetime_as_timestamp=True` to encode as UNIX timestamp integer/float (CBOR Tag 1)
190
+ **note:** this replaces timezone information as UTC.
191
+ Naive `datetime` s are assumed to be UTC, which is also how timestamps are interpreted when structuring.
192
+
193
+ ```{versionchanged} 26.2.0
194
+ Naive `datetime` s are assumed to be UTC when unstructuring.
195
+ They were previously interpreted as local time, making the serialized value depend on the timezone of the machine doing the unstructuring.
196
+ ```
197
+
198
+ `date` s are serialized as ISO 8601 strings.
199
+
200
+ Use keyword argument `canonical=True` for efficient encoding to the smallest binary output.
201
+
202
+ Floats can be forced to smaller output by casting to lower-precision formats by casting to `numpy` floats (and back to Python floats).
203
+ Example: `float(np.float32(value))` or `float(np.float16(value))`
204
+
205
+ ```{versionadded} 23.1.0
206
+
207
+ ```
208
+
209
+ ## _bson_
210
+
211
+ Found at {mod}`cattrs.preconf.bson`. Tested against the _bson_ module bundled with the _pymongo_ library, not the standalone PyPI _bson_ package.
212
+
213
+ Sets are serialized as lists, and deserialized back into sets.
214
+
215
+ _bson_ doesn't support integers less than -9223372036854775808 or greater than 9223372036854775807 (64-bit signed).
216
+ _bson_ does not support null bytes in mapping keys.
217
+ _bson_ only supports mappings with string keys so mappings will have their keys stringified before serialization, and destringified during deserialization.
218
+ The _bson_ datetime representation doesn't support microsecond accuracy.
219
+ `date` s are serialized as ISO 8601 strings.
220
+
221
+ When encoding and decoding, the library needs to be passed `codec_options=bson.CodecOptions(tz_aware=True)` to get the full range of compatibility.
222
+
223
+
224
+ ## _pyyaml_
225
+
226
+ Found at {mod}`cattrs.preconf.pyyaml`.
227
+
228
+ Frozensets are serialized as lists, and deserialized back into frozensets.
229
+ `date` s are serialized as ISO 8601 strings.
230
+ Typed named tuples are unstructured into ordinary tuples, and then into YAML arrays by _pyyaml_.
231
+
232
+ ## _tomlkit_
233
+
234
+ Found at {mod}`cattrs.preconf.tomlkit`.
235
+
236
+ Bytes are serialized as base 85 strings. Sets are serialized as lists, and deserialized back into sets.
237
+ Tuples are serialized as lists, and deserialized back into tuples.
238
+ _tomlkit_ only supports mappings with string keys so mappings will have their keys stringified before serialization, and destringified during deserialization.
239
+ [`date`](https://docs.python.org/3/library/datetime.html#datetime.date) and [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) objects are passed through to be unstructured by _tomlkit_ itself.
tasks/tasksmith-c756db832cf4/tests/source/docs/recipes.md ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Recipes
2
+
3
+ This page contains a collection of recipes for custom un-/structuring mechanisms.
4
+
5
+
6
+ ## Switching Initializers
7
+
8
+ When structuring _attrs_ classes, _cattrs_ uses the classes' ``__init__`` method to instantiate objects by default.
9
+ In certain situations, you might want to deviate from this behavior and use alternative initializers instead.
10
+
11
+ For example, consider the following `Point` class describing points in 2D space, which offers two `classmethod`s for alternative creation:
12
+
13
+ ```{doctest} point_group
14
+ >>> import math
15
+ >>> from attrs import define
16
+
17
+ >>> @define
18
+ ... class Point:
19
+ ... """A point in 2D space."""
20
+ ... x: float
21
+ ... y: float
22
+ ...
23
+ ... @classmethod
24
+ ... def from_tuple(cls, coordinates: tuple[float, float]) -> "Point":
25
+ ... """Create a point from a tuple of Cartesian coordinates."""
26
+ ... return Point(*coordinates)
27
+ ...
28
+ ... @classmethod
29
+ ... def from_polar(cls, radius: float, angle: float) -> "Point":
30
+ ... """Create a point from its polar coordinates."""
31
+ ... return Point(radius * math.cos(angle), radius * math.sin(angle))
32
+ ```
33
+
34
+
35
+ ### Selecting an Alternative Initializer
36
+
37
+ A simple way to _statically_ set one of the `classmethod`s as initializer is to register a structuring hook that holds a reference to the respective callable:
38
+
39
+ ```{doctest} point_group
40
+ >>> from inspect import signature
41
+ >>> from typing import Callable, TypedDict
42
+
43
+ >>> from cattrs import Converter
44
+ >>> from cattrs.dispatch import StructureHook
45
+
46
+ >>> def signature_to_typed_dict(fn: Callable) -> type[TypedDict]:
47
+ ... """Create a TypedDict reflecting a callable's signature."""
48
+ ... params = {p: t.annotation for p, t in signature(fn).parameters.items()}
49
+ ... return TypedDict(f"{fn.__name__}_args", params)
50
+ ...
51
+
52
+ >>> def make_initializer_from(fn: Callable, conv: Converter) -> StructureHook:
53
+ ... """Return a structuring hook from a given callable."""
54
+ ... td = signature_to_typed_dict(fn)
55
+ ... td_hook = conv.get_structure_hook(td)
56
+ ... return lambda v, _: fn(**td_hook(v, td))
57
+ ```
58
+
59
+ Now, you can easily structure `Point`s from the specified alternative representation:
60
+
61
+ ```{doctest} point_group
62
+ >>> c = Converter()
63
+ >>> c.register_structure_hook(Point, make_initializer_from(Point.from_polar, c))
64
+
65
+ >>> p0 = Point(1.0, 0.0)
66
+ >>> p1 = c.structure({"radius": 1.0, "angle": 0.0}, Point)
67
+ >>> assert p0 == p1
68
+ ```
69
+
70
+
71
+ ### Dynamically Switching Between Initializers
72
+
73
+ In some cases, even more flexibility is required and the selection of the initializer must happen at runtime, requiring a dynamic approach.
74
+ A typical scenario would be when object structuring happens behind an API and you want to let the user specify which representation of the object they wish to provide in their serialization string.
75
+
76
+ In such situations, the following hook factory can help you achieve your goal:
77
+
78
+ ```{doctest} point_group
79
+ >>> from inspect import signature
80
+ >>> from typing import Callable, TypedDict
81
+
82
+ >>> from cattrs import Converter
83
+ >>> from cattrs.dispatch import StructureHook
84
+
85
+ >>> def signature_to_typed_dict(fn: Callable) -> type[TypedDict]:
86
+ ... """Create a TypedDict reflecting a callable's signature."""
87
+ ... params = {p: t.annotation for p, t in signature(fn).parameters.items()}
88
+ ... return TypedDict(f"{fn.__name__}_args", params)
89
+
90
+ >>> T = TypeVar("T")
91
+ >>> def make_initializer_selection_hook(
92
+ ... initializer_key: str,
93
+ ... converter: Converter,
94
+ ... ) -> StructureHook:
95
+ ... """Return a structuring hook that dynamically switches between initializers."""
96
+ ...
97
+ ... def select_initializer_hook(specs: dict, cls: type[T]) -> T:
98
+ ... """Deserialization with dynamic initializer selection."""
99
+ ...
100
+ ... # If no initializer keyword is specified, use regular __init__
101
+ ... if initializer_key not in specs:
102
+ ... return converter.structure_attrs_fromdict(specs, cls)
103
+ ...
104
+ ... # Otherwise, call the specified initializer with deserialized arguments
105
+ ... specs = specs.copy()
106
+ ... initializer_name = specs.pop(initializer_key)
107
+ ... initializer = getattr(cls, initializer_name)
108
+ ... td = signature_to_typed_dict(initializer)
109
+ ... td_hook = converter.get_structure_hook(td)
110
+ ... return initializer(**td_hook(specs, td))
111
+ ...
112
+ ... return select_initializer_hook
113
+ ```
114
+
115
+ Specifying the key that determines the initializer to be used now lets you dynamically select the `classmethod` as part of the object specification itself:
116
+
117
+ ```{doctest} point_group
118
+ >>> c = Converter()
119
+ >>> c.register_structure_hook(Point, make_initializer_selection_hook("initializer", c))
120
+
121
+ >>> p0 = Point(1.0, 0.0)
122
+ >>> p1 = c.structure({"initializer": "from_polar", "radius": 1.0, "angle": 0.0}, Point)
123
+ >>> p2 = c.structure({"initializer": "from_tuple", "coordinates": (1.0, 0.0)}, Point)
124
+ >>> assert p0 == p1 == p2
125
+ ```
tasks/tasksmith-c756db832cf4/tests/source/docs/strategies.md ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Strategies
2
+
3
+ _cattrs_ ships with a number of _strategies_ for customizing un/structuring behavior.
4
+
5
+ Strategies are prepackaged, high-level patterns for quickly and easily applying complex customizations to a converter.
6
+
7
+ ## Tagged Unions Strategy
8
+
9
+ _Found at {py:func}`cattrs.strategies.configure_tagged_union`._
10
+
11
+ The _tagged union_ strategy allows for un/structuring a union of classes by including an additional field (the _tag_) in the unstructured representation.
12
+ Each tag value is associated with a member of the union.
13
+
14
+ ```{doctest} tagged_unions
15
+
16
+ >>> from cattrs.strategies import configure_tagged_union
17
+ >>> from cattrs import Converter
18
+ >>> converter = Converter()
19
+
20
+ >>> @define
21
+ ... class A:
22
+ ... a: int
23
+
24
+ >>> @define
25
+ ... class B:
26
+ ... b: str
27
+
28
+ >>> configure_tagged_union(A | B, converter)
29
+
30
+ >>> converter.unstructure(A(1), unstructure_as=A | B)
31
+ {'a': 1, '_type': 'A'}
32
+
33
+ >>> converter.structure({'a': 1, '_type': 'A'}, A | B)
34
+ A(a=1)
35
+ ```
36
+
37
+ By default, the tag field name is `_type` and the tag value is the class name of the union member.
38
+ Both the field name and value can be overriden.
39
+
40
+ The `tag_generator` parameter is a one-argument callable that will be called with every member of the union to generate a mapping of tag values to union members.
41
+ Here are some common `tag_generator` uses:
42
+
43
+ | Tag info available in | Recommended `tag_generator` |
44
+ | ----------------------------- | ------------------------------------------------------- |
45
+ | Name of the class | Use the default, or `lambda cl: cl.__name__` |
46
+ | A class variable (`classvar`) | `lambda cl: cl.classvar` |
47
+ | A dictionary (`mydict`) | `mydict.get` or `mydict.__getitem__` |
48
+ | An enum of possible values | Build a dictionary of classes to enum values and use it |
49
+
50
+ The union members aren't required to be attrs classes or dataclasses, although those work automatically.
51
+ They may be anything that cattrs can un/structure from/to a dictionary, for example a type with registered custom hooks.
52
+
53
+ A default member can be specified to be used if the tag is missing or is unknown.
54
+ This is useful for evolving APIs in a backwards-compatible way; an endpoint taking class `A` can be changed to take `A | B` with `A` as the default (for old clients which do not send the tag).
55
+
56
+ This strategy only applies in the context of the union; the normal un/structuring hooks are left untouched.
57
+ This also means union members can be reused in multiple unions easily.
58
+
59
+ ```{doctest} tagged_unions
60
+
61
+ # Unstructuring as a union.
62
+ >>> converter.unstructure(A(1), unstructure_as=A | B)
63
+ {'a': 1, '_type': 'A'}
64
+
65
+ # Unstructuring as just an `A`.
66
+ >>> converter.unstructure(A(1))
67
+ {'a': 1}
68
+ ```
69
+
70
+ ```{versionchanged} 25.1.0
71
+ The strategy can also be called with a type alias of a union.
72
+ ```
73
+
74
+ ### Real-life Case Study
75
+
76
+ The Apple App Store supports [server callbacks](https://developer.apple.com/documentation/appstoreservernotifications), by which Apple sends a JSON payload to a URL of your choice.
77
+ The payload can be interpreted as about a dozen different messages, based on the value of the `notificationType` field.
78
+
79
+ To keep the example simple we define two classes, one for the `REFUND` event and one for everything else.
80
+
81
+ ```{testcode} apple
82
+
83
+ @define
84
+ class Refund:
85
+ originalTransactionId: str
86
+
87
+ @define
88
+ class OtherAppleNotification:
89
+ notificationType: str
90
+
91
+ AppleNotification = Refund | OtherAppleNotification
92
+
93
+ ```
94
+
95
+ Next, we use the _tagged unions_ strategy to prepare our converter.
96
+ The tag value for the `Refund` event is `REFUND`, and we can let the `OtherAppleNotification` class handle all the other cases.
97
+ The `tag_generator` parameter is a callable, so we can give it the `get` method of a dictionary.
98
+
99
+ ```{doctest} apple
100
+
101
+ >>> from cattrs.strategies import configure_tagged_union
102
+
103
+ >>> c = Converter()
104
+ >>> configure_tagged_union(
105
+ ... AppleNotification,
106
+ ... c,
107
+ ... tag_name="notificationType",
108
+ ... tag_generator={Refund: "REFUND"}.get,
109
+ ... default=OtherAppleNotification
110
+ ... )
111
+
112
+ ```
113
+
114
+ The converter is now ready to start structuring Apple notifications.
115
+
116
+ ```{doctest} apple
117
+
118
+ >>> payload = {"notificationType": "REFUND", "originalTransactionId": "1"}
119
+ >>> notification = c.structure(payload, AppleNotification)
120
+
121
+ >>> match notification:
122
+ ... case Refund(txn_id):
123
+ ... print(f"Refund for {txn_id}!")
124
+ ... case OtherAppleNotification(not_type):
125
+ ... print("Can't handle this yet")
126
+ Refund for 1!
127
+ ```
128
+
129
+ ```{versionadded} 23.1.0
130
+
131
+ ```
132
+
133
+ ## Include Subclasses Strategy
134
+
135
+ _Found at {py:func}`cattrs.strategies.include_subclasses`._
136
+
137
+ The _include subclass_ strategy allows the un/structuring of a base class to an instance of itself or one of its descendants.
138
+ Conceptually with this strategy, each time an un/structure operation for the base class is asked, `cattrs` machinery replaces that operation as if the union of the base class and its descendants had been asked instead.
139
+
140
+ ```{doctest} include_subclass
141
+
142
+ >>> from attrs import define
143
+ >>> from cattrs.strategies import include_subclasses
144
+ >>> from cattrs import Converter
145
+
146
+ >>> @define
147
+ ... class Parent:
148
+ ... a: int
149
+
150
+ >>> @define
151
+ ... class Child(Parent):
152
+ ... b: str
153
+
154
+ >>> converter = Converter()
155
+ >>> include_subclasses(Parent, converter)
156
+
157
+ >>> converter.unstructure(Child(a=1, b="foo"), unstructure_as=Parent)
158
+ {'a': 1, 'b': 'foo'}
159
+
160
+ >>> converter.structure({'a': 1, 'b': 'foo'}, Parent)
161
+ Child(a=1, b='foo')
162
+ ```
163
+
164
+ In the example above, we asked to unstructure then structure a `Child` instance as the `Parent` class and in both cases we correctly obtained back the unstructured and structured versions of the `Child` instance.
165
+ If we did not apply the `include_subclasses` strategy, this is what we would have obtained:
166
+
167
+ ```python
168
+ >>> converter_no_subclasses = Converter()
169
+
170
+ >>> converter_no_subclasses.unstructure(Child(a=1, b="foo"), unstructure_as=Parent)
171
+ {'a': 1}
172
+
173
+ >>> converter_no_subclasses.structure({'a': 1, 'b': 'foo'}, Parent)
174
+ Parent(a=1)
175
+ ```
176
+
177
+ Without the application of the strategy, in both unstructure and structure operations, we received a `Parent` instance.
178
+
179
+ ```{note}
180
+ The handling of subclasses is an opt-in feature for two main reasons:
181
+ - Performance. While small and probably negligible in most cases the subclass handling incurs more function calls and has a performance impact.
182
+ - Customization. The specific handling of subclasses can be different from one situation to the other. In particular there is not apparent universal good defaults for disambiguating the union type. Consequently the decision is left to the user.
183
+ ```
184
+
185
+ ```{warning}
186
+ To work properly, all subclasses must be defined when the `include_subclasses` strategy is applied to a `converter`. If subclasses types are defined later, for instance in the context of a plug-in mechanism using inheritance, then those late defined subclasses will not be part of the subclasses union type and will not be un/structured as expected.
187
+ ```
188
+
189
+ ### Customization
190
+
191
+ In the example shown in the previous section, the default options for `include_subclasses` work well because the `Child` class has an attribute that do not exist in the `Parent` class (the `b` attribute).
192
+ The automatic union type disambiguation function which is based on finding unique fields for each type of the union works as intended.
193
+
194
+ Sometimes, more disambiguation customization is required.
195
+ For instance, the unstructuring operation would have failed if `Child` did not have an extra attribute or if a sibling of `Child` had also a `b` attribute.
196
+ For those cases, a callable of 2 positional arguments (a union type and a converter) defining a [tagged union strategy](strategies.md#tagged-unions-strategy) can be passed to the `include_subclasses` strategy.
197
+ {py:func}`configure_tagged_union()<cattrs.strategies.configure_tagged_union>` can be used as-is, but if you want to change its defaults, the [partial](https://docs.python.org/3/library/functools.html#functools.partial) function from the `functools` module in the standard library can come in handy.
198
+
199
+ ```python
200
+
201
+ >>> from functools import partial
202
+ >>> from attrs import define
203
+ >>> from cattrs.strategies import include_subclasses, configure_tagged_union
204
+ >>> from cattrs import Converter
205
+
206
+ >>> @define
207
+ ... class Parent:
208
+ ... a: int
209
+
210
+ >>> @define
211
+ ... class Child1(Parent):
212
+ ... b: str
213
+
214
+ >>> @define
215
+ ... class Child2(Parent):
216
+ ... b: int
217
+
218
+ >>> converter = Converter()
219
+ >>> union_strategy = partial(configure_tagged_union, tag_name="type_name")
220
+ >>> include_subclasses(Parent, converter, union_strategy=union_strategy)
221
+
222
+ >>> converter.unstructure(Child1(a=1, b="foo"), unstructure_as=Parent)
223
+ {'a': 1, 'b': 'foo', 'type_name': 'Child1'}
224
+
225
+ >>> converter.structure({'a': 1, 'b': 1, 'type_name': 'Child2'}, Parent)
226
+ Child2(a=1, b=1)
227
+ ```
228
+
229
+ Other customizations available see are (see {py:func}`include_subclasses()<cattrs.strategies.include_subclasses>`):
230
+
231
+ - The exact list of subclasses that should participate to the union with the `subclasses` argument.
232
+ - Attribute overrides that permit the customization of attributes un/structuring like renaming an attribute.
233
+
234
+ Here is an example involving both customizations:
235
+
236
+ ```python
237
+
238
+ >>> from attrs import define
239
+ >>> from cattrs.strategies import include_subclasses
240
+ >>> from cattrs import Converter, override
241
+
242
+ >>> @define
243
+ ... class Parent:
244
+ ... a: int
245
+
246
+ >>> @define
247
+ ... class Child(Parent):
248
+ ... b: str
249
+
250
+ >>> converter = Converter()
251
+ >>> include_subclasses(
252
+ ... Parent,
253
+ ... converter,
254
+ ... subclasses=(Parent, Child),
255
+ ... overrides={"b": override(rename="c")}
256
+ ... )
257
+
258
+ >>> converter.unstructure(Child(a=1, b="foo"), unstructure_as=Parent)
259
+ {'a': 1, 'c': 'foo'}
260
+
261
+ >>> converter.structure({'a': 1, 'c': 'foo'}, Parent)
262
+ Child(a=1, b='foo')
263
+ ```
264
+
265
+ ```{versionadded} 23.1.0
266
+
267
+ ```
268
+
269
+ ## Using Class-Specific Structure and Unstructure Methods
270
+
271
+ _Found at {py:func}`cattrs.strategies.use_class_methods`._
272
+
273
+ This strategy allows for un/structuring logic on the models themselves.
274
+ It can be applied for both structuring and unstructuring (also simultaneously).
275
+
276
+ If a class requires special handling for (un)structuring, you can add a dedicated (un)structuring
277
+ method:
278
+
279
+ ```{doctest} class_methods
280
+
281
+ >>> from attrs import define
282
+ >>> from cattrs import Converter
283
+ >>> from cattrs.strategies import use_class_methods
284
+
285
+ >>> @define
286
+ ... class MyClass:
287
+ ... a: int
288
+ ...
289
+ ... @classmethod
290
+ ... def _structure(cls, data: dict):
291
+ ... return cls(data["b"] + 1) # expecting "b", not "a"
292
+ ...
293
+ ... def _unstructure(self):
294
+ ... return {"c": self.a - 1} # unstructuring as "c", not "a"
295
+
296
+ >>> converter = Converter()
297
+ >>> use_class_methods(converter, "_structure", "_unstructure")
298
+ >>> print(converter.structure({"b": 42}, MyClass))
299
+ MyClass(a=43)
300
+ >>> print(converter.unstructure(MyClass(42)))
301
+ {'c': 41}
302
+ ```
303
+
304
+ Any class without a `_structure` or `_unstructure` method will use the default strategy for structuring or unstructuring, respectively.
305
+ Feel free to use other names.
306
+ The stategy can be applied multiple times (with different method names).
307
+
308
+ If you want to (un)structured nested objects, just append a converter parameter to your (un)structuring methods and you will receive the converter there:
309
+
310
+ ```{doctest} class_methods
311
+
312
+ >>> @define
313
+ ... class Nested:
314
+ ... m: MyClass
315
+ ...
316
+ ... @classmethod
317
+ ... def _structure(cls, data: dict, conv):
318
+ ... return cls(conv.structure(data["n"], MyClass))
319
+ ...
320
+ ... def _unstructure(self, conv):
321
+ ... return {"n": conv.unstructure(self.m)}
322
+
323
+ >>> print(converter.structure({"n": {"b": 42}}, Nested))
324
+ Nested(m=MyClass(a=43))
325
+ >>> print(converter.unstructure(Nested(MyClass(42))))
326
+ {'n': {'c': 41}}
327
+ ```
328
+
329
+ ```{versionadded} 23.2.0
330
+
331
+ ```
332
+
333
+ ## Union Passthrough
334
+
335
+ _Found at {py:func}`cattrs.strategies.configure_union_passthrough`._
336
+
337
+ The _union passthrough_ strategy enables a {py:class}`Converter <cattrs.BaseConverter>` to structure unions and subunions of given types.
338
+
339
+ A very common use case for _cattrs_ is processing data created by other serialization libraries, such as _JSON_ or _msgpack_.
340
+ These libraries are able to directly produce values of unions inherent to the format.
341
+ For example, every JSON library can differentiate between numbers, booleans, strings and null values since these values are represented differently in the wire format.
342
+ This strategy enables _cattrs_ to offload the creation of these values to an underlying library and just validate the final value.
343
+ So, _cattrs_ preconfigured JSON converters can handle the following type:
344
+
345
+ - `bool | int | float | str | None`
346
+
347
+ Continuing the JSON example, this strategy also enables structuring subsets of unions of these values.
348
+ Accordingly, here are some examples of subset unions that are also supported:
349
+
350
+ - `bool | int`
351
+ - `int | str`
352
+ - `int | float | str`
353
+
354
+ The strategy also supports types including one or more [Literals](https://mypy.readthedocs.io/en/stable/literal_types.html#literal-types) of supported types. For example:
355
+
356
+ - `Literal["admin", "user"] | int`
357
+ - `Literal[True] | str | int | float`
358
+
359
+ The strategy also supports [NewTypes](https://mypy.readthedocs.io/en/stable/more_types.html#newtypes) of these types. For example:
360
+
361
+ ```python
362
+ >>> from typing import NewType
363
+
364
+ >>> UserId = NewType("UserId", int)
365
+
366
+ >>> converter.loads("12", UserId)
367
+ 12
368
+ ```
369
+
370
+ ```{versionchanged} 26.2.0
371
+ PEP 695 type aliases of supported types are supported when used as union members.
372
+ ```
373
+
374
+ Unions containing unsupported types can be handled if at least one union type is supported by the strategy; the supported union types will be checked before the rest (referred to as the _spillover_) is handed over to the converter again.
375
+
376
+ For example, if `A` and `B` are arbitrary _attrs_ classes, the union `Literal[10] | A | B` cannot be handled directly by a JSON converter.
377
+ However, the strategy will check if the value being structured matches `Literal[10]` (because this type _is_ supported) and, if not, will pass it back to the converter to be structured as `A | B` (where a different strategy can handle it).
378
+
379
+ The strategy is designed to run in _O(1)_ at structure time; it doesn't depend on the size of the union and the ordering of union members.
380
+
381
+ This strategy has been preapplied to the following preconfigured converters:
382
+
383
+ - {py:class}`BsonConverter <cattrs.preconf.bson.BsonConverter>`
384
+ - {py:class}`Cbor2Converter <cattrs.preconf.cbor2.Cbor2Converter>`
385
+ - {py:class}`JsonConverter <cattrs.preconf.json.JsonConverter>`
386
+ - {py:class}`MsgpackConverter <cattrs.preconf.msgpack.MsgpackConverter>`
387
+ - {py:class}`MsgspecJsonConverter <cattrs.preconf.msgspec.MsgspecJsonConverter>`
388
+ - {py:class}`OrjsonConverter <cattrs.preconf.orjson.OrjsonConverter>`
389
+ - {py:class}`PyyamlConverter <cattrs.preconf.pyyaml.PyyamlConverter>`
390
+ - {py:class}`TomlkitConverter <cattrs.preconf.tomlkit.TomlkitConverter>`
391
+ - {py:class}`UjsonConverter <cattrs.preconf.ujson.UjsonConverter>`
392
+
393
+ ```{versionadded} 23.2.0
394
+
395
+ ```
tasks/tasksmith-c756db832cf4/tests/source/docs/unions.md ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Handling Unions
2
+
3
+ _cattrs_ is able to handle simple unions of _attrs_ classes and dataclasses [automatically](#default-union-strategy).
4
+ More complex cases require converter customization (since there are many ways of handling unions).
5
+
6
+ _cattrs_ also comes with a number of optional strategies to help handle unions:
7
+
8
+ - [tagged unions strategy](strategies.md#tagged-unions-strategy) mentioned below
9
+ - [union passthrough strategy](strategies.md#union-passthrough), which is preapplied to all the [preconfigured](preconf.md) converters
10
+
11
+ ## Default Union Strategy
12
+
13
+ For convenience, _cattrs_ includes a default union structuring strategy which is a little more opinionated.
14
+
15
+ Given a union of several _attrs_ classes and/or dataclasses, the default union strategy will attempt to handle it in several ways.
16
+
17
+ First, it will look for `Literal` fields.
18
+ If _all members_ of the union contain a literal field, _cattrs_ will generate a disambiguation function based on the field.
19
+
20
+ ```python
21
+ from typing import Literal
22
+
23
+ @define
24
+ class ClassA:
25
+ field_one: Literal["one"]
26
+
27
+ @define
28
+ class ClassB:
29
+ field_one: Literal["two"] = "two"
30
+ ```
31
+
32
+ In this case, a payload containing `{"field_one": "one"}` will produce an instance of `ClassA`.
33
+
34
+ ````{note}
35
+ The following snippet can be used to disable the use of literal fields, restoring legacy behavior.
36
+
37
+ ```python
38
+ from functools import partial
39
+ from cattrs.disambiguators import is_supported_union
40
+
41
+ converter.register_structure_hook_factory(
42
+ is_supported_union,
43
+ partial(converter._gen_attrs_union_structure, use_literals=False),
44
+ )
45
+ ```
46
+
47
+ ````
48
+
49
+ If there are no appropriate fields, the strategy will examine the classes for **unique required fields**.
50
+
51
+ So, given a union of `ClassA` and `ClassB`:
52
+
53
+ ```python
54
+ @define
55
+ class ClassA:
56
+ field_one: str
57
+ field_with_default: str = "a default"
58
+
59
+ @define
60
+ class ClassB:
61
+ field_two: str
62
+ ```
63
+
64
+ the strategy will determine that if a payload contains the key `field_one` it should be handled as `ClassA`, and if it contains the key `field_two` it should be handled as `ClassB`.
65
+ The field `field_with_default` will not be considered since it has a default value, so it gets treated as optional.
66
+
67
+ ```{versionchanged} 23.2.0
68
+ Literals can now be potentially used to disambiguate.
69
+ ```
70
+
71
+ ```{versionchanged} 24.1.0
72
+ Dataclasses are now supported in addition to _attrs_ classes.
73
+ ```
74
+
75
+ ## Unstructuring Unions with Extra Metadata
76
+
77
+ ```{note}
78
+ _cattrs_ comes with the [tagged unions strategy](strategies.md#tagged-unions-strategy) for handling this exact use-case since version 23.1.
79
+ The example below has been left here for educational purposes, but you should prefer the strategy.
80
+ ```
81
+
82
+ Let's assume a simple scenario of two classes, `ClassA` and `ClassB`, both
83
+ of which have no distinct fields and so cannot be used automatically with
84
+ _cattrs_.
85
+
86
+ ```python
87
+ @define
88
+ class ClassA:
89
+ a_string: str
90
+
91
+ @define
92
+ class ClassB:
93
+ a_string: str
94
+ ```
95
+
96
+ A naive approach to unstructuring either of these would yield identical
97
+ dictionaries, and not enough information to restructure the classes.
98
+
99
+ ```python
100
+ >>> converter.unstructure(ClassA("test"))
101
+ {'a_string': 'test'} # Is this ClassA or ClassB? Who knows!
102
+ ```
103
+
104
+ What we can do is ensure some extra information is present in the
105
+ unstructured data, and then use that information to help structure later.
106
+
107
+ First, we register an unstructure hook for the `Union[ClassA, ClassB]` type.
108
+
109
+ ```python
110
+ >>> converter.register_unstructure_hook(
111
+ ... Union[ClassA, ClassB],
112
+ ... lambda o: {"_type": type(o).__name__, **converter.unstructure(o)}
113
+ ... )
114
+ >>> converter.unstructure(ClassA("test"), unstructure_as=Union[ClassA, ClassB])
115
+ {'_type': 'ClassA', 'a_string': 'test'}
116
+ ```
117
+
118
+ Note that when unstructuring, we had to provide the `unstructure_as` parameter
119
+ or _cattrs_ would have just applied the usual unstructuring rules to `ClassA`,
120
+ instead of our special union hook.
121
+
122
+ Now that the unstructured data contains some information, we can create a
123
+ structuring hook to put it to use:
124
+
125
+ ```python
126
+ >>> converter.register_structure_hook(
127
+ ... Union[ClassA, ClassB],
128
+ ... lambda o, _: converter.structure(o, ClassA if o["_type"] == "ClassA" else ClassB)
129
+ ... )
130
+ >>> converter.structure({"_type": "ClassA", "a_string": "test"}, Union[ClassA, ClassB])
131
+ ClassA(a_string='test')
132
+ ```
tasks/tasksmith-c756db832cf4/tests/source/docs/usage.md ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Advanced Examples
2
+
3
+ This section covers advanced use examples of _cattrs_ features.
4
+
5
+ ## Using Factory Hooks
6
+
7
+ For this example, let's assume you have some attrs classes with snake case attributes, and you want to un/structure them as camel case.
8
+
9
+ ```{warning}
10
+ A simpler and better approach to this problem is to simply make your class attributes camel case.
11
+ However, this is a good example of the power of hook factories and _cattrs'_ composition-based design.
12
+ ```
13
+
14
+ Here's our simple data model:
15
+
16
+ ```python
17
+ @define
18
+ class Inner:
19
+ a_snake_case_int: int
20
+ a_snake_case_float: float
21
+ a_snake_case_str: str
22
+
23
+ @define
24
+ class Outer:
25
+ a_snake_case_inner: Inner
26
+ ```
27
+
28
+ Let's examine our options one by one, starting with the simplest: writing manual un/structuring hooks.
29
+
30
+ We just write the code by hand and register it:
31
+
32
+ ```python
33
+ def unstructure_inner(inner):
34
+ return {
35
+ "aSnakeCaseInt": inner.a_snake_case_int,
36
+ "aSnakeCaseFloat": inner.a_snake_case_float,
37
+ "aSnakeCaseStr": inner.a_snake_case_str
38
+ }
39
+
40
+ >>> converter.register_unstructure_hook(Inner, unstructure_inner)
41
+ ```
42
+
43
+ (Let's skip the other unstructure hook and 2 structure hooks due to verbosity.)
44
+
45
+ This will get us where we want to go, but the drawbacks are immediately obvious:
46
+ we'd need to write a ton of code ourselves, wasting effort, increasing our
47
+ maintenance burden and risking bugs. Obviously this won't do.
48
+
49
+ Why write code when we can write code to write code for us? In this case this
50
+ code has already been written for you. _cattrs_ contains a module,
51
+ {mod}`cattrs.gen`, with functions to automatically generate hooks exactly like this.
52
+ These functions also take parameters to customize the generated hooks.
53
+
54
+ We can generate and register the renaming hooks we need:
55
+
56
+ ```python
57
+ >>> from cattrs.gen import make_dict_unstructure_fn, override
58
+
59
+ >>> converter.register_unstructure_hook(
60
+ ... Inner,
61
+ ... make_dict_unstructure_fn(
62
+ ... Inner,
63
+ ... converter,
64
+ ... a_snake_case_int=override(rename="aSnakeCaseInt"),
65
+ ... a_snake_case_float=override(rename="aSnakeCaseFloat"),
66
+ ... a_snake_case_str=override(rename="aSnakeCaseStr"),
67
+ ... )
68
+ ... )
69
+ ```
70
+
71
+ (Again skipping the other hooks due to verbosity.)
72
+
73
+ This is still too verbose and manual for our tastes, so let's automate it
74
+ further. We need a way to convert snake case identifiers to camel case, so
75
+ let's grab one from Stack Overflow:
76
+
77
+ ```python
78
+ def to_camel_case(snake_str: str) -> str:
79
+ components = snake_str.split("_")
80
+ return components[0] + "".join(x.title() for x in components[1:])
81
+ ```
82
+
83
+ We can combine this with [`attrs.fields`](https://www.attrs.org/en/stable/api.html#attrs.fields) to save us some typing:
84
+
85
+ ```python
86
+ from attrs import fields
87
+ from cattrs.gen import make_dict_unstructure_fn, override
88
+
89
+ converter.register_unstructure_hook(
90
+ Inner,
91
+ make_dict_unstructure_fn(
92
+ Inner,
93
+ converter,
94
+ **{a.name: override(rename=to_camel_case(a.name)) for a in fields(Inner)}
95
+ )
96
+ )
97
+
98
+ converter.register_unstructure_hook(
99
+ Outer,
100
+ make_dict_unstructure_fn(
101
+ Outer,
102
+ converter,
103
+ **{a.name: override(rename=to_camel_case(a.name)) for a in fields(Outer)}
104
+ )
105
+ )
106
+ ```
107
+
108
+ (Skipping the structuring hooks due to verbosity.)
109
+
110
+ Now we're getting somewhere, but we still need to do this for each class
111
+ separately. The final step is using hook factories instead of hooks directly.
112
+
113
+ Hook factories are functions that return hooks. They are also registered using
114
+ predicates instead of being attached to classes directly, like normal
115
+ un/structure hooks. Predicates are functions that given a type return a
116
+ boolean whether they handle it.
117
+
118
+ We want our hook factories to trigger for all _attrs_ classes, so we need a
119
+ predicate to recognize whether a type is an _attrs_ class. Luckily, _attrs_ comes
120
+ with [`attrs.has`](https://www.attrs.org/en/stable/api.html#attrs.has), which is exactly this.
121
+
122
+ As the final step, we can combine all of this into two hook factories:
123
+
124
+ ```python
125
+ from attrs import has, fields
126
+ from cattrs import Converter
127
+ from cattrs.gen import make_dict_unstructure_fn, make_dict_structure_fn, override
128
+
129
+ converter = Converter()
130
+
131
+ def to_camel_case(snake_str: str) -> str:
132
+ components = snake_str.split("_")
133
+ return components[0] + "".join(x.title() for x in components[1:])
134
+
135
+ def to_camel_case_unstructure(cls):
136
+ return make_dict_unstructure_fn(
137
+ cls,
138
+ converter,
139
+ **{
140
+ a.name: override(rename=to_camel_case(a.name))
141
+ for a in fields(cls)
142
+ }
143
+ )
144
+
145
+ def to_camel_case_structure(cls):
146
+ return make_dict_structure_fn(
147
+ cls,
148
+ converter,
149
+ **{
150
+ a.name: override(rename=to_camel_case(a.name))
151
+ for a in fields(cls)
152
+ }
153
+ )
154
+
155
+ converter.register_unstructure_hook_factory(
156
+ has, to_camel_case_unstructure
157
+ )
158
+ converter.register_structure_hook_factory(
159
+ has, to_camel_case_structure
160
+ )
161
+ ```
162
+
163
+ The `converter` instance will now un/structure every attrs class to camel case.
164
+ Nothing has been omitted from this final example; it's complete.
165
+
166
+
167
+ ## Using Fallback Key Names
168
+
169
+ Sometimes when structuring data, the input data may be in multiple formats that need to be converted into a common attribute.
170
+
171
+ Consider an example where a data store creates a new schema version and renames a key (ie, `{'old_field': 'value1'}` in v1 becomes `{'new_field': 'value1'}` in v2), while also leaving existing records in the system with the V1 schema. Both keys should convert to the same field.
172
+
173
+ Here, builtin customizations such as [rename](./customizing.md#rename) are insufficient - _cattrs_ cannot structure both `old_field` and `new_field` into a single field using `rename`, at least not on the same converter.
174
+
175
+ In order to support both fields, you can apply a little preprocessing to the default _cattrs_ structuring hooks.
176
+ One approach is to write the following decorator and apply it to your class.
177
+
178
+ ```python
179
+ from attrs import define
180
+ from cattrs import Converter
181
+ from cattrs.gen import make_dict_structure_fn
182
+
183
+ converter = Converter()
184
+
185
+
186
+ def fallback_field(
187
+ converter_arg: Converter,
188
+ old_to_new_field: dict[str, str]
189
+ ):
190
+ def decorator(cls):
191
+ struct = make_dict_structure_fn(cls, converter_arg)
192
+
193
+ def structure(d, cl):
194
+ for k, v in old_to_new_field.items():
195
+ if k in d:
196
+ d[v] = d[k]
197
+
198
+ return struct(d, cl)
199
+
200
+ converter_arg.register_structure_hook(cls, structure)
201
+
202
+ return cls
203
+
204
+ return decorator
205
+
206
+
207
+ @fallback_field(converter, {"old_field": "new_field"})
208
+ @define
209
+ class MyInternalAttr:
210
+ new_field: str
211
+ ```
212
+
213
+ _cattrs_ will now structure both key names into `new_field` on your class.
214
+
215
+ ```python
216
+ converter.structure({"new_field": "foo"}, MyInternalAttr)
217
+ converter.structure({"old_field": "foo"}, MyInternalAttr)
218
+ ```
tasks/tasksmith-c756db832cf4/tests/source/docs/validation.md ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Validation
2
+
3
+ _cattrs_ has a detailed validation mode since version 22.1.0, and this mode is enabled by default.
4
+ When running under detailed validation, the structuring hooks are slightly slower but produce richer and more precise error messages.
5
+ Unstructuring hooks are not affected.
6
+
7
+ ## Detailed Validation
8
+
9
+ ```{versionadded} 22.1.0
10
+
11
+ ```
12
+ In detailed validation mode, any structuring errors will be grouped and raised together as a {class}`cattrs.BaseValidationError`, which is a [PEP 654 ExceptionGroup](https://www.python.org/dev/peps/pep-0654/).
13
+ ExceptionGroups are special exceptions which contain lists of other exceptions, which may themselves be other ExceptionGroups.
14
+ In essence, ExceptionGroups are trees of exceptions.
15
+
16
+ When structuring a class, _cattrs_ will gather any exceptions on a field-by-field basis and raise them as a {class}`cattrs.ClassValidationError`, which is a subclass of {class}`BaseValidationError <cattrs.BaseValidationError>`.
17
+
18
+ When structuring sequences and mappings, _cattrs_ will gather any exceptions on a key- or index-basis and raise them as a {class}`cattrs.IterableValidationError`, which is a subclass of {class}`BaseValidationError <cattrs.BaseValidationError>`.
19
+
20
+ The exceptions will also have their `__notes__` attributes set, as per [PEP 678](https://www.python.org/dev/peps/pep-0678/), showing the field, key or index for each inner exception.
21
+
22
+ A simple example involving a class containing a list and a dictionary:
23
+
24
+ ```python
25
+ @define
26
+ class Class:
27
+ a_list: list[int]
28
+ a_dict: dict[str, int]
29
+
30
+ >>> structure({"a_list": ["a"], "a_dict": {"str": "a"}}, Class)
31
+ + Exception Group Traceback (most recent call last):
32
+ | File "<stdin>", line 1, in <module>
33
+ | File "/Users/tintvrtkovic/pg/cattrs/src/cattr/converters.py", line 276, in structure
34
+ | return self._structure_func.dispatch(cl)(obj, cl)
35
+ | File "<cattrs generated structure __main__.Class>", line 14, in structure_Class
36
+ | if errors: raise __c_cve('While structuring Class', errors, __cl)
37
+ | cattrs.errors.ClassValidationError: While structuring Class
38
+ +-+---------------- 1 ----------------
39
+ | Exception Group Traceback (most recent call last):
40
+ | File "<cattrs generated structure __main__.Class>", line 5, in structure_Class
41
+ | res['a_list'] = __c_structure_a_list(o['a_list'], __c_type_a_list)
42
+ | File "/Users/tintvrtkovic/pg/cattrs/src/cattr/converters.py", line 457, in _structure_list
43
+ | raise IterableValidationError(
44
+ | cattrs.errors.IterableValidationError: While structuring list[int]
45
+ | Structuring class Class @ attribute a_list
46
+ +-+---------------- 1 ----------------
47
+ | Traceback (most recent call last):
48
+ | File "/Users/tintvrtkovic/pg/cattrs/src/cattr/converters.py", line 450, in _structure_list
49
+ | res.append(handler(e, elem_type))
50
+ | File "/Users/tintvrtkovic/pg/cattrs/src/cattr/converters.py", line 375, in _structure_call
51
+ | return cl(obj)
52
+ | ValueError: invalid literal for int() with base 10: 'a'
53
+ | Structuring list[int] @ index 0
54
+ +------------------------------------
55
+ +---------------- 2 ----------------
56
+ | Exception Group Traceback (most recent call last):
57
+ | File "<cattrs generated structure __main__.Class>", line 10, in structure_Class
58
+ | res['a_dict'] = __c_structure_a_dict(o['a_dict'], __c_type_a_dict)
59
+ | File "", line 17, in structure_mapping
60
+ | cattrs.errors.IterableValidationError: While structuring dict
61
+ | Structuring class Class @ attribute a_dict
62
+ +-+---------------- 1 ----------------
63
+ | Traceback (most recent call last):
64
+ | File "", line 5, in structure_mapping
65
+ | ValueError: invalid literal for int() with base 10: 'a'
66
+ | Structuring mapping value @ key 'str'
67
+ +------------------------------------
68
+ ```
69
+
70
+ ### Transforming Exceptions into Error Messages
71
+
72
+ ```{versionadded} 23.1.0
73
+
74
+ ```
75
+
76
+ ExceptionGroup stack traces are useful while developing, but sometimes a more compact representation of validation errors is required.
77
+ _cattrs_ provides a helper function, {func}`cattrs.transform_error`, which transforms validation errors into lists of error messages.
78
+
79
+ The example from the previous paragraph produces the following error messages:
80
+
81
+ ```{testsetup} class
82
+ @define
83
+ class Class:
84
+ a_list: list[int]
85
+ a_dict: dict[str, int]
86
+ ```
87
+
88
+ ```{doctest} class
89
+
90
+ >>> from cattrs import structure, transform_error
91
+
92
+ >>> try:
93
+ ... structure({"a_list": ["a"], "a_dict": {"str": "a"}}, Class)
94
+ ... except Exception as exc:
95
+ ... print(transform_error(exc))
96
+ ['invalid value for type, expected int @ $.a_list[0]', "invalid value for type, expected int @ $.a_dict['str']"]
97
+ ```
98
+
99
+ A small number of built-in exceptions are converted into error messages automatically.
100
+ This can be further customized by providing {func}`cattrs.transform_error` with a function that it can use to turn individual, non-ExceptionGroup exceptions into error messages.
101
+ A useful pattern is wrapping the default, {func}`cattrs.v.format_exception` function.
102
+
103
+ ```
104
+ >>> from cattrs.v import format_exception
105
+
106
+ >>> def my_exception_formatter(exc: BaseException, type) -> str:
107
+ ... if isinstance(exc, MyInterestingException):
108
+ ... return "My error message"
109
+ ... return format_exception(exc, type)
110
+
111
+ >>> try:
112
+ ... structure(..., Class)
113
+ ... except Exception as exc:
114
+ ... print(transform_error(exc, format_exception=my_exception_formatter))
115
+ ```
116
+
117
+ If even more customization is required, {func}`cattrs.transform_error` can be copied over into your codebase and adjusted as needed.
118
+
119
+ ## Non-detailed Validation
120
+
121
+ Non-detailed validation can be enabled by initializing any of the converters with `detailed_validation=False`.
122
+ In this mode, any errors during un/structuring will bubble up directly as soon as they happen.
tasks/tasksmith-c756db832cf4/tests/source/docs/why.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Why *cattrs*?
2
+
3
+ Python has a rich set of powerful, easy to use, built-in **unstructured** data types like dictionaries, lists and tuples.
4
+ These data types effortlessly convert into common serialization formats like JSON, MessagePack, CBOR, YAML or TOML.
5
+
6
+ But the data that is used by your **business logic** should be **structured** into well-defined classes, since not all combinations of field names or values are valid inputs to your programs.
7
+ The more trust you can have into the structure of your data, the simpler your code can be, and the fewer edge cases you have to worry about.
8
+
9
+ When you're handed unstructured data (by your network, file system, database, ...), _cattrs_ helps to convert this data into trustworthy structured data.
10
+ When you have to convert your structured data into data types that other libraries can handle, _cattrs_ turns your classes and enumerations into dictionaries, integers and strings.
11
+
12
+ _attrs_ (and to a certain degree dataclasses) are excellent libraries for declaratively describing the structure of your data, but they're purposefully not serialization libraries.
13
+ *cattrs* is there for you the moment your `attrs.asdict(your_instance)` and `YourClass(**data)` start failing you because you need more control over the conversion process.
14
+
15
+
16
+ ## Examples
17
+
18
+ ```{include} ../README.md
19
+ :start-after: "begin-example -->"
20
+ :end-before: "<!-- end-example"
21
+ ```
22
+
23
+ :::{important}
24
+ Note how the structuring and unstructuring details do **not** pollute your class, meaning: your data model.
25
+ Any needs to configure the conversion are done within *cattrs* itself, not within your data model.
26
+
27
+ There are popular validation libraries for Python that couple your data model with its validation and serialization rules based on, for example, web APIs.
28
+ We think that's the wrong approach.
29
+ Validation and serializations are concerns of the edges of your program – not the core.
30
+ They should neither apply design pressure on your business code, nor affect the performance of your code through unnecessary validation.
31
+ In bigger real-world code bases it's also common for data coming from multiple sources that need different validation and serialization rules.
32
+
33
+ 🎶 You gotta keep 'em separated. 🎶
34
+ :::
35
+
36
+
37
+ *cattrs* also works with the usual Python collection types like dictionaries, lists, or tuples when you want to **normalize** unstructured data data into a certain (still unstructured) shape.
38
+ For example, to convert a list of a float, an int and a string into a tuple of ints:
39
+
40
+ ```python
41
+ >>> import cattrs
42
+
43
+ >>> cattrs.structure([1.0, 2, "3"], tuple[int, int, int])
44
+ (1, 2, 3)
45
+
46
+ ```
47
+
48
+ Finally, here's a much more complex example, involving _attrs_ classes where _cattrs_ interprets the type annotations to structure and unstructure the data correctly, including Enums and nested data structures:
49
+
50
+ ```python
51
+ >>> from enum import unique, Enum
52
+ >>> from typing import Sequence
53
+ >>> from cattrs import structure, unstructure
54
+ >>> from attrs import define, field
55
+
56
+ >>> @unique
57
+ ... class CatBreed(Enum):
58
+ ... SIAMESE = "siamese"
59
+ ... MAINE_COON = "maine_coon"
60
+ ... SACRED_BIRMAN = "birman"
61
+
62
+ >>> @define
63
+ ... class Cat:
64
+ ... breed: CatBreed
65
+ ... names: Sequence[str]
66
+
67
+ >>> @define
68
+ ... class DogMicrochip:
69
+ ... chip_id = field() # Type annotations are optional, but recommended
70
+ ... time_chipped: float = field()
71
+
72
+ >>> @define
73
+ ... class Dog:
74
+ ... cuteness: int
75
+ ... chip: DogMicrochip | None = None
76
+
77
+ >>> p = unstructure([Dog(cuteness=1, chip=DogMicrochip(chip_id=1, time_chipped=10.0)),
78
+ ... Cat(breed=CatBreed.MAINE_COON, names=('Fluffly', 'Fluffer'))])
79
+
80
+ >>> p
81
+ [{'cuteness': 1, 'chip': {'chip_id': 1, 'time_chipped': 10.0}}, {'breed': 'maine_coon', 'names': ['Fluffly', 'Fluffer']}]
82
+ >>> structure(p, list[Dog | Cat])
83
+ [Dog(cuteness=1, chip=DogMicrochip(chip_id=1, time_chipped=10.0)), Cat(breed=<CatBreed.MAINE_COON: 'maine_coon'>, names=['Fluffly', 'Fluffer'])]
84
+
85
+ ```
86
+
87
+ :::{tip}
88
+ Consider unstructured data a low-level representation that needs to be converted to structured data to be handled, and use `structure()`.
89
+ When you're done, `unstructure()` the data to its unstructured form and pass it along to another library or module.
90
+ :::
91
+
92
+
93
+ ```{include} ../README.md
94
+ :start-after: "begin-why -->"
95
+ :end-before: "<!-- end-why"
96
+ ```
97
+
98
+
99
+ ## Additional Documentation and Talks
100
+
101
+ - [On structured and unstructured data, or the case for cattrs](https://threeofwands.com/on-structured-and-unstructured-data-or-the-case-for-cattrs/)
102
+ - [Why I use attrs instead of pydantic](https://threeofwands.com/why-i-use-attrs-instead-of-pydantic/)
103
+ - [cattrs I: un/structuring speed](https://threeofwands.com/why-cattrs-is-so-fast/)
104
+ - [Python has a macro language - it's Python (PyCon IT 2022)](https://www.youtube.com/watch?v=UYRSixikUTo)
105
+ - [Intro to cattrs 23.1](https://threeofwands.com/intro-to-cattrs-23-1-0/)
tasks/tasksmith-c756db832cf4/tests/source/pyproject.toml ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [dependency-groups]
2
+ lint = [
3
+ "ruff>=0.12.2",
4
+ ]
5
+ test = [
6
+ "hypothesis>=6.135.26",
7
+ "pytest>=8.4.1",
8
+ "pytest-typing; python_version == '3.14' and implementation_name == 'cpython'",
9
+ "mypy; python_version == '3.14' and implementation_name == 'cpython'",
10
+ "pytest-benchmark>=5.1.0",
11
+ "immutables>=0.21",
12
+ "coverage>=7.9.2",
13
+ "pytest-xdist>=3.8.0",
14
+ ]
15
+ docs = [
16
+ "sphinx>=5.3.0",
17
+ "furo>=2024.1.29",
18
+ "sphinx-copybutton>=0.5.2",
19
+ "myst-parser>=1.0.0",
20
+ "pendulum>=3.1.0",
21
+ "sphinx-autobuild",
22
+ ]
23
+ bench = [
24
+ "pyperf>=2.6.1",
25
+ ]
26
+
27
+ [build-system]
28
+ requires = ["hatchling", "hatch-vcs"]
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.mypy]
32
+ strict = true
33
+
34
+ [tool.pytest]
35
+ addopts = [
36
+ "-l",
37
+ "--benchmark-sort=fullname",
38
+ "--benchmark-warmup=true",
39
+ "--benchmark-warmup-iterations=5",
40
+ "--benchmark-group-by=fullname",
41
+ ]
42
+ typing_checkers = ["mypy"]
43
+
44
+ [project]
45
+ name = "cattrs"
46
+ description = "Composable complex class support for attrs and dataclasses."
47
+ authors = [
48
+ {name = "Tin Tvrtkovic", email = "tinchester@gmail.com"},
49
+ ]
50
+ dependencies = [
51
+ "attrs>=25.4.0",
52
+ "typing-extensions>=4.14.0",
53
+ "exceptiongroup>=1.1.1; python_version < '3.11'",
54
+ ]
55
+ requires-python = ">=3.10"
56
+ readme = "README.md"
57
+ license = {text = "MIT"}
58
+ keywords = ["attrs", "serialization", "dataclasses"]
59
+ classifiers = [
60
+ "Development Status :: 5 - Production/Stable",
61
+ "Intended Audience :: Developers",
62
+ "License :: OSI Approved :: MIT License",
63
+ "Programming Language :: Python :: 3.10",
64
+ "Programming Language :: Python :: 3.11",
65
+ "Programming Language :: Python :: 3.12",
66
+ "Programming Language :: Python :: 3.13",
67
+ "Programming Language :: Python :: 3.14",
68
+ "Programming Language :: Python :: Implementation :: CPython",
69
+ "Programming Language :: Python :: Implementation :: PyPy",
70
+ "Typing :: Typed",
71
+ ]
72
+ dynamic = ["version"]
73
+
74
+ [project.urls]
75
+ Homepage = "https://catt.rs"
76
+ Changelog = "https://catt.rs/en/latest/history.html"
77
+ "Bug Tracker" = "https://github.com/python-attrs/cattrs/issues"
78
+ Repository = "https://github.com/python-attrs/cattrs"
79
+ Documentation = "https://catt.rs/en/stable/"
80
+
81
+ [project.optional-dependencies]
82
+ ujson = [
83
+ "ujson>=5.10.0",
84
+ ]
85
+ orjson = [
86
+ "orjson>=3.11.3; implementation_name == \"cpython\"",
87
+ ]
88
+ msgpack = [
89
+ "msgpack>=1.0.5",
90
+ ]
91
+ pyyaml = [
92
+ "PyYAML>=6.0",
93
+ ]
94
+ tomlkit = [
95
+ "tomlkit>=0.11.8",
96
+ ]
97
+ cbor2 = [
98
+ "cbor2>=5.4.6",
99
+ ]
100
+ bson = [
101
+ "pymongo>=4.4.0",
102
+ ]
103
+ msgspec = [
104
+ "msgspec>=0.21.1; implementation_name == \"cpython\"",
105
+ ]
106
+ tomllib = [
107
+ "tomli>=1.1.0; python_version < '3.11'",
108
+ "tomli-w>=1.1.0",
109
+ ]
110
+
111
+ [tool.coverage.run]
112
+ parallel = true
113
+ source_pkgs = ["cattrs", "tests"]
114
+ core = "sysmon"
115
+ patch = ["subprocess"]
116
+
117
+ [tool.coverage.report]
118
+ show_missing = true
119
+ skip_covered = true
120
+ skip_empty = true
121
+ exclude_also = [
122
+ "@overload",
123
+ "if TYPE_CHECKING:",
124
+ ]
125
+
126
+ [tool.ruff]
127
+ src = ["src", "tests"]
128
+
129
+ [tool.ruff.per-file-target-version]
130
+ "*_695.py" = "py312"
131
+
132
+ [tool.ruff.lint]
133
+ select = [
134
+ "E", # pycodestyle
135
+ "W", # pycodestyle
136
+ "F", # Pyflakes
137
+ "UP", # pyupgrade
138
+ "N", # pep8-naming
139
+ "YTT", # flake8-2020
140
+ "S", # flake8-bandit
141
+ "B", # flake8-bugbear
142
+ "C4", # flake8-comprehensions
143
+ "T10", # flake8-debugger
144
+ "T20", # flake8-print
145
+ "ISC", # flake8-implicit-str-concat
146
+ "RET", # flake8-return
147
+ "SIM", # flake8-simplify
148
+ "DTZ", # flake8-datetimez
149
+ "PGH", # pygrep-hooks
150
+ "PLC", # Pylint
151
+ "PIE", # flake8-pie
152
+ "RUF", # ruff
153
+ "I", # isort
154
+ ]
155
+ ignore = [
156
+ "E501", # line length is handled by the formatter
157
+ "RUF001", # leave my smart characters alone
158
+ "S101", # assert
159
+ "S307", # hands off my eval
160
+ "SIM300", # Yoda rocks in asserts
161
+ "PGH003", # leave my type: ignores alone
162
+ "B006", # mutable argument defaults
163
+ "B905", # zip strictness, too noisy
164
+ "DTZ001", # datetimes in tests
165
+ "DTZ006", # datetimes in tests
166
+ "UP006", # We support old typing constructs at runtime
167
+ "UP007", # We support old typing constructs at runtime
168
+ "UP035", # We support old typing constructs at runtime
169
+ "UP045", # We support old typing constructs at runtime
170
+ ]
171
+
172
+ [tool.ruff.lint.pyupgrade]
173
+ # Preserve types, even if a file imports `from __future__ import annotations`.
174
+ keep-runtime-typing = true
175
+
176
+ [tool.ruff.lint.isort]
177
+ split-on-trailing-comma = false
178
+
179
+ [tool.ruff.format]
180
+ skip-magic-trailing-comma = true
181
+
182
+ [tool.hatch.version]
183
+ source = "vcs"
184
+ raw-options = { local_scheme = "no-local-version" }
185
+
186
+ [tool.hatch.build.targets.wheel]
187
+ packages = ["src/cattr", "src/cattrs"]
188
+
189
+ [tool.check-wheel-contents]
190
+ toplevel = ["cattr", "cattrs"]
tasks/tasksmith-c756db832cf4/tests/source/src/cattr/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .converters import BaseConverter, Converter, GenConverter, UnstructureStrategy
2
+ from .gen import override
3
+
4
+ __all__ = (
5
+ "BaseConverter",
6
+ "Converter",
7
+ "GenConverter",
8
+ "UnstructureStrategy",
9
+ "global_converter",
10
+ "override",
11
+ "structure",
12
+ "structure_attrs_fromdict",
13
+ "structure_attrs_fromtuple",
14
+ "unstructure",
15
+ )
16
+ from cattrs import global_converter
17
+
18
+ unstructure = global_converter.unstructure
19
+ structure = global_converter.structure
20
+ structure_attrs_fromtuple = global_converter.structure_attrs_fromtuple
21
+ structure_attrs_fromdict = global_converter.structure_attrs_fromdict
22
+ register_structure_hook = global_converter.register_structure_hook
23
+ register_structure_hook_func = global_converter.register_structure_hook_func
24
+ register_unstructure_hook = global_converter.register_unstructure_hook
25
+ register_unstructure_hook_func = global_converter.register_unstructure_hook_func
tasks/tasksmith-c756db832cf4/tests/source/src/cattr/converters.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from cattrs.converters import (
2
+ BaseConverter,
3
+ Converter,
4
+ GenConverter,
5
+ UnstructureStrategy,
6
+ )
7
+
8
+ __all__ = ["BaseConverter", "Converter", "GenConverter", "UnstructureStrategy"]
tasks/tasksmith-c756db832cf4/tests/source/src/cattr/disambiguators.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from cattrs.disambiguators import create_uniq_field_dis_func
2
+
3
+ __all__ = ["create_uniq_field_dis_func"]
tasks/tasksmith-c756db832cf4/tests/source/src/cattr/dispatch.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from cattrs.dispatch import FunctionDispatch, MultiStrategyDispatch
2
+
3
+ __all__ = ["FunctionDispatch", "MultiStrategyDispatch"]