How to change default values of dataclass attributes dynamically?

Viewed 312

I would like to know if it is possible to change (dynamically) a default argument value in a dataclass, to achieve something like this:

from dataclasses import dataclass

@dataclass
class Foo:
    bar = "foobar"

Foo.bar = "world"

foo1 = Foo(bar="hello")  # foo1.bar = "hello"
foo2 = Foo()  # foo2.bar = "world"
1 Answers

You should inherit your dataclass:

from dataclasses import dataclass

@dataclass
class Foo:
    bar = "foobar"

Foo.bar = "world"

foo1 = Foo(bar="hello")  # foo1.bar = "hello"
foo2 = Foo()  # foo2.bar = "world"

from dataclasses import dataclass

@dataclass
class NewFoo(Foo):
    bar = "world"



foo1 = Foo(bar="hello")  # foo1.bar = "hello"
foo2 = NewFoo()  # foo2.bar = "world"

Related