cattrs
cattrs copied to clipboard
Error with adapted_fields when subclassing attr class
- 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
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.
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 ?
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.