Skip to content

Adding keys to unstructure dict #584

Closed
@isohedronpipeline

Description

@isohedronpipeline
  • cattrs version: 24.2.0
  • Python version: 3.10
  • Operating System: Windows

Description

I have an attrs class with a bunch of subclasses. These attrs dataclasses point to other attrs dataclasses.
I would like to take control of the way it unstructures myself, such that the resulting dictionary has an extra key.

I am specifically looking to add a fully dotted path to the class so that I can use pydoc.locate to find the class instead of relying on the cattrs subclass scheme, which should allow me to avoid importing everything first and avoid a problem with subclasses that happen to be named the same.

If the data type was a "leaf" then I could simply call

result = attrs.asdict(obj)
result["_type_path"] = get_fully_dotted_path_to_class(obj.__class__)

But since the class has a container of other types that need unstructure hooks, I can't use attrs.asdict(). I need to use the unstructuriing dispatcher.

What I Did

I tried to do this:

def unstructure_job(obj: Any) -> Any:
    result = converter._unstructure_func.dispatch(obj.__class__)(obj)
    result['_type_path'] = get_dotted_path_to_class(obj.__class__)
    return result

But that ends up with an infinite recursion.

How can I hop in the middle to add a new key?

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions