biqqles / dataclassy

A fast and flexible reimplementation of data classes
https://pypi.org/project/dataclassy
Mozilla Public License 2.0
81 stars 9 forks source link

Mutable default values shared between instances #17

Closed hohav closed 3 years ago

hohav commented 3 years ago

Is this intended behavior?

from dataclassy import dataclass

@dataclass
class Foo:
    bar = []

>>> a = Foo()
>>> b = Foo()
>>> a.bar.append(1)
>>> b.bar
[1]

I get the same results on the last two stable releases (0.7.0 and 0.6.2). If I'm reading correctly, the README says it's not intended:

A shallow copy will be created for mutable arguments (defined as those defining a copy method). This means that default field values that are mutable (e.g. a list) will not be mutated between instances.

biqqles commented 3 years ago

Ah, this is because the attribute has no type annotation!

You can exclude a class attribute from dataclassy's mechanisms entirely by simply defining it without a type annotation. This can be used for class variables and constants.

hohav commented 3 years ago

Ah, my bad. I keep forgetting about the type annotation requirement.