Home > Back-end >  Dataclass not instantiating variables
Dataclass not instantiating variables

Time:06-07

import time
from dataclasses import dataclass


@dataclass
class Test:

    ts=time.time()


while 1:
    m = Test()
    print(m.ts)
    time.sleep(2)

With this code, I would expect the time to be increasing by 2 every time, but it is staying constant. How can I get the time to refresh everytime the dataclass is instantiated?

CodePudding user response:

You want an instance attribute, not a class attribute, that gets initialized to the current time. Use dataclasses.field to configure the class to use a default factory to define the ts field if no explicit value is given on instantiation.

from dataclasses import dataclass, field
import time


@dataclass
class Test:
    ts: float = field(default_factory=time.time)

Then you can use the default

>>> Test().ts
1654541245.673183

or provide an explicit timestamp (for testing, if nothing else)

>>> Test(3.14159).ts
3.14159
  • Related