Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow field overrides via Annotated #604

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

slykar
Copy link

@slykar slykar commented Nov 24, 2024

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:

@slykar slykar force-pushed the override-with-annotated branch from 3ddc9a8 to 7c98e50 Compare November 24, 2024 15:07
fields_with_specific_annotation = (
(
field_name,
next((a for a in annotations if isinstance(a, annotation_type_)), None),
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function will only find annotations that were instantiated, which works fine for the purpose of finding annotations created by gen.override()

@Tinche
Copy link
Member

Tinche commented Nov 25, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants