Python dataclass setting default list with values

Viewed 5901

Can anyone help me fix this error. I just started using dataclass I wanted to put a default value so I can easily call from other function

I have this class

@dataclass(frozen=True)
class MyClass:
    my_list: list = ["list1", "list2", "list3"]
    my_list2: list = ["list1", "list2", "list3"]

But when i print print(MyClass.my_list) I'm getting this error

 raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'list'> for field my_list is not allowed: use default_factory
2 Answers

What it means by mutable default is that the lists provided as defaults will be the same individual objects in each instance of the dataclass. This would be confusing because mutating the list in an instance by e.g. appending to it would also append to the list in every other instance.

Instead, it wants you to provide a default_factory function that will make a new list for each instance:

from dataclasses import dataclass, field

@dataclass
class MyClass:
    my_list: list = field(default_factory=lambda: ["list1", "list2", "list3"])
    my_list2: list = field(default_factory=lambda: ["list1", "list2", "list3"])

As the first comment notes, it's a bit odd to have a mutable item in a dataclass. If you don't need it to be mutable, a simpler solution is to initialize it as a tuple.

from dataclasses import dataclass

@dataclass
class MyClass:
    my_list: tuple(str) = ("list1", "list2", "list3")
    my_list2: tuple(str) = ("list1", "list2", "list3")

(For example, you might want a tuple of fieldnames associated with your dataclass for serialization with DictWriter.)

Related