Ragnar
Ragnar

Reputation: 2690

Dataclass - how to have a mutable list as field

I want to use the new @dataclass decorator in my code with attribut as mutable list Something that would look like this

from dataclasses import dataclass

@dataclass
class Metrics
    accuracy: list = []
    loss: list = []

...

def do_stuff(data):
    m = Metrics()

    for i in range(0, 10):
        m.accuracy.append(accuracy_def(i))
        m.loss.append(loss_def(i))

    return m

But I have this error:

TypeError: __init__() missing 2 required positional arguments: 'accuracy' and 'loss'

Upvotes: 1

Views: 3190

Answers (1)

Filip Młynarski
Filip Młynarski

Reputation: 3612

Use dataclasses.field() instead

@dataclass
class Metrics:
    accuracy: List[int] = field(default_factory=list)
    loss: List[int] = field(default_factory=list)

Upvotes: 4

Related Questions