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

Feature Request: Use dedicated (un)structure methods if available #394

Closed
pohlt opened this issue Jul 14, 2023 · 5 comments
Closed

Feature Request: Use dedicated (un)structure methods if available #394

pohlt opened this issue Jul 14, 2023 · 5 comments

Comments

@pohlt
Copy link
Contributor

pohlt commented Jul 14, 2023

To (uns)structure certain objects, cattrs allows to register (un)structure hooks. This is a great way to allow (un)structuring of any object, in particular if I cannot modify the underlying classes.

If I have control over the classes, it could be easier to define a (un)structure function or property within the class itself, because this code would reside within each class. During (un)structuring, cattrs could look for the availability of such functions and use the accordingly.

One way to implement that would be to tell the converter to look for a certain method/property (_structure in the example below):

converter.register_structure_property("_structure")

What to you think?

BTW: Thanks a lot for cattrs. I love it!

@Tinche
Copy link
Member

Tinche commented Jul 18, 2023

Howdy!

So this is actually pretty easy to set up I think. You need to use a predicate function, here's the code:

from attrs import define

from cattrs import Converter


@define
class MyClass:
    a: int

    @classmethod
    def structure(cls, data: dict):
        return cls(data["b"])  # Not a


c = Converter()

c.register_structure_hook_func(
    lambda t: hasattr(t, "structure"), lambda v, t: t.structure(v)
)

print(c.structure({"b": 1}, MyClass))

Since it's already a one-liner (depending on the length of your method name ;) maybe we just document this somewhere?

If you feel like contributing something more substantial, I'd be open to making this a strategy (see here).

@pohlt
Copy link
Contributor Author

pohlt commented Jul 19, 2023

That's awesome, thanks a lot!

I was looking into register_structure_hook_func, but considered it unhelpful for my idea. D'oh! 🙅🏼
Let's see if I find the time to add it as a strategy.

@pohlt
Copy link
Contributor Author

pohlt commented Jul 24, 2023

Here's a PR.

@pohlt
Copy link
Contributor Author

pohlt commented Aug 10, 2023

Here's a new PR: #405

@Tinche
Copy link
Member

Tinche commented Nov 19, 2023

Closing since this was merged.

@Tinche Tinche closed this as completed Nov 19, 2023
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

No branches or pull requests

2 participants