python-attrs / cattrs

Composable custom class converters for attrs, dataclasses and friends.
https://catt.rs
MIT License
828 stars 113 forks source link

Lambda passed to register_unstructure_hook is not called for an instance when instance is in an inherited field #335

Open aljohnston112 opened 1 year ago

aljohnston112 commented 1 year ago

Description

I have a @frozen class that inherits a @frozen class containing two enums PType and Split. I am trying to write the class to a file using json.dumps. Unfortunately the unstructure_hook I provided is not getting called and as a result I get an Exception when dumping to json. I expect the PType unstructure_hook I provided to allow the class to be written to json.

What I Did

Here is the code that causes the exception. I have verified that the unstructure_hook I provided to c is never called.

    with open(MOVES_FILE_OUT, "w") as fo:
        c = cattrs.Converter()
        c.register_unstructure_hook(
            PType, lambda pt: pt.name
        )
        fo.write(json.dumps(c.unstructure(moves)))

This is the exception

TypeError: Object of type PType is not JSON serializable

My understanding is that the convertor calls the unstructure_hook when it sees a PType and coverts it to the type returned by the lambda (a str here), but it appears to miss the PType fields.

aljohnston112 commented 1 year ago

Hm, I switched to GenConverter and it correctly unstructures now.