cattrs icon indicating copy to clipboard operation
cattrs copied to clipboard

converters are mutate despite deepcopy

Open GiorgioBalestrieri opened this issue 3 years ago • 2 comments

  • cattrs version: 1.0.0
  • Python version: 3.7
  • Operating System: MacOS

Description

When creating a copy.deepcopy of a cattrs Converter instance, and registering structure/unstructure hooks to the copy, the original Converter instance also ends up having those hooks, which isn't expected.

This makes it very hard to create specialized copies of a converter, or to make temporary changes to a converter for specific purposes.

What I Did

from cattr.converters import Converter
import copy
import attr

conv = Converter()

@attr.s(auto_attribs=True)
class A:
    x: int
    

def unstructure_a(a: A):
    # adding a message so that we can spot when the hook is being used
    print("using custom unstructure hook")
    return {"x": a.x}

other_conv = copy.deepcopy(conv)

other_conv.register_unstructure_hook(A, unstructure_a)

other_conv.unstructure(A(1))
# prints "using custom unstructure hook" (as expected)

conv.unstructure(A(1))
# prints "using custom unstructure hook" (unexpected)

To make this even more confusing, the two copies have different hashes:

hash(conv) == hash(other_conv)
# returns False

GiorgioBalestrieri avatar Apr 26 '22 17:04 GiorgioBalestrieri

Yep, better copying is on the roadmap (possibly for the next version). It's been requested several times now.

Tinche avatar Apr 26 '22 17:04 Tinche

@Tinche thanks for the quick response. Do you have a sense of what's the underlying issue? As in, why does copy.deepcopy not work as expected?

GiorgioBalestrieri avatar May 02 '22 18:05 GiorgioBalestrieri

Copying is done now, and released in 22.2.0!

Tinche avatar Oct 12 '22 10:10 Tinche