Skip to content

Converter copy does not copy unstructure hooks #398

@danielnelson

Description

@danielnelson
  • cattrs version: 23.1.2
  • Python version: 3.9.17
  • Operating System: Gentoo

Description

I wanted to create a base Converter with some common unstructuring hooks, then copy it in other places and add extra hooks. After copying the Converter I found that the unstructuring hooks from the source Converter no longer work.

What I Did

from dataclasses import dataclass
from functools import partial
from typing import Any

import cattrs


@dataclass
class C:
    value: int


@dataclass
class D:
    child: Any


# https://github.com/python-attrs/cattrs/issues/320
def _unstructure_any(converter, value):
    return converter.unstructure(value, unstructure_as=value.__class__)


converter = cattrs.Converter()
converter.register_unstructure_hook_func(
    lambda t: t is Any, partial(_unstructure_any, converter)
)
d = D(child=C(value=42))
actual = converter.unstructure(d)
expected = {"child": {"value": 42}}
assert expected == actual

converter = converter.copy()
d = D(child=C(value=42))
actual = converter.unstructure(d)
expected = {"child": {"value": 42}}
assert expected == actual, "failure"
Traceback (most recent call last):
  File "tmp.py", line 36, in <module>
    assert expected == actual, "failure"
AssertionError: failure

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions