cattrs icon indicating copy to clipboard operation
cattrs copied to clipboard

Error with adapted_fields when subclassing attr class

Open cp2587 opened this issue 3 years ago • 3 comments

  • cattrs version: 1.8.0
  • Python version: 3.8
  • Operating System: PopOS

Description

The current implementation of adapted_fields check first if the type if a dataclass when you should instead test if it's a attr class first. This leads to miscategorizing type as non attr class and not use the attrs_fields

What I Did

    @strawberry.type  # definie method typical of python dataclass that gets picked up by cattr.is_dataclass
    @attr.define
    class UserAttributes:
        birthday: Optional[date] = attr.field(validator=attr.validators.optional(attr.validators.instance_of(date)),
                                              default=None)
    structure({}, UserAttributes)  # fails with KeyError 'birthday' because the default of attr is not handled

cp2587 avatar Apr 22 '22 19:04 cp2587

We don't support classes that are both a dataclass and an attrs class. Checking out the library you mentioned, that's what's happening.

I don't have plans to enable this since this is the first time I've seen something like this and I don't think it's worth it. You can either ask Strawberry to support attrs classes, or just use strawberry.type to get a dataclass - cattrs supports dataclasses.

Tinche avatar Apr 22 '22 22:04 Tinche

Ok understood. In any case my logic is a bit more complex and so i ended up monkey patching adapted_fields in cattr - do you think it would be useful to have a way for client library to supersede the default adapted_fields with their own ?

cp2587 avatar Apr 23 '22 12:04 cp2587

Probably yes in the future, although I'm not quite sure what that API would look like exactly.

In the main time, here's a way to do this now: https://replit.com/@TinTvrtkovic/cattrs257#main.py

I've set up a structure hook factory which makes cattrs believe this is not a dataclass while it's generating the hook, and then restores it.

Tinche avatar Apr 24 '22 12:04 Tinche