Is it possible to create distinct instances of dataclass?
from dataclasses import dataclass
from datetime import datetime
from time import sleep
class A:
def __init__(self):
self.time = datetime.now()
a1 = A().time
sleep(1)
a2 = A().time
assert a1 != a2
The above works fine. Let's now try the same with dataclass.
@dataclass
class B:
time = datetime.now()
b1 = B().time
sleep(1)
b2 = B().time
assert b1 != b2 # does not work
The benefit is avoiding sugary self
but is it at the cost of creating class specific attributes instead of instance attributes via init
?
Maybe dataclass should be used only when one instance is possible?
CodePudding user response:
dataclass
is a class decorator that modifies the decorated class after it's been defined. Since datetime.now()
is evaluated and assigned to the time
class attribute at the time of the class definition, it is too late for the dataclass
decorator to wrap the expression into an __init__
method as the expression has already been evaluated into a fixed value.
Instead, the dataclasses
module offers a field
method with a default_factory
parameter to produce value for an attribute at runtime during the call to __init__
, so that your code can work as intended as follows:
from dataclasses import dataclass, field
from datetime import datetime
@dataclass
class B:
time: datetime = field(default_factory=datetime.now)
b1 = B().time
b2 = B().time
assert b1 != b2