python-attrs / python-attrs/cattrs

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

Open
#335 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.1k
Forks
159
Avg merge
12h 21m
Merged PRs (30d)
6

Description

  • cattrs version: 22.2.0
  • Python version: 3.11
  • Operating System: Windows 10
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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the example with cattrs 22.2.0 on Python 3.11, including the inherited frozen classes and registered PType hook. Trace unstructuring of the inherited fields and verify that the PType hook is called and json.dumps accepts the resulting value.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.