cattrs icon indicating copy to clipboard operation
cattrs copied to clipboard

Allow field overrides via `Annotated`

Open slykar opened this issue 1 year ago • 1 comments

Here's a simple implementation of using Annotated to provide field overrides. Please let me know where's the best place for this code or feel free to move it somewhere else.

Tests could also be improved (I just moved them from another project).

Refs:

  • #571

slykar avatar Nov 24 '24 15:11 slykar

A pretty good start!

Here's how I would proceed, but let me know if you run into difficulties and we need to rethink.

Let's introduce a new module, cattrs.annotated, and add a helper method to it, something like: find_annotated_metadata(type: Any, metadata_cls: type[T]) -> T | Nothing. We can leave this module undocumented for now, but it can be a building block for us and users later on. It should return the first instance of metadata_cls in the Annotated, if there is one and the type is really Annotated, otherwise attrs.Nothing. We can also move our existing is_annotated helper here from _compat.

Then we can use this helper method to extract instances of AttributeOverride from types. I wouldn't do the extraction in make_dict_unstructure_fn but deeper, in make_dict_unstructure_fn_from_attrs and make_dict_structure_fn_from_attrs. That way the NamedTuple factory can also benefit from it.

This helper method should also be used in gen/typeddicts so TypedDicts can also benefit.

Tinche avatar Nov 25 '24 15:11 Tinche