You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Dataclass实例化时动态生成唯一时间戳的实现原理疑问

Why does dataclass require field(default_factory) for dynamic timestamps instead of direct default values?

Great question—this is a super common pitfall with Python dataclasses (and Python in general!), so let's break down exactly what's happening here.

The problem with your first approach

When you write:

@dataclass
class test:
    timestamp: datetime = datetime.utcnow()

Python executes the datetime.utcnow() call the moment the class is defined, not when you create an instance. All default values for class attributes (and function parameters, for that matter) are evaluated once at definition time, not each time you use them.

That means when you run this code, Python calculates the UTC time right away, stores that single datetime object as the default for the timestamp field, and every instance you create afterwards just reuses that same pre-computed value. No wonder all your timestamps are identical!

Why field(default_factory) works

The default_factory parameter in dataclasses.field() is specifically designed for cases where you need a dynamic default value—something that's generated fresh each time you create an instance.

Instead of evaluating the function at class definition time, default_factory tells the dataclass: "Every time someone creates a new instance, call this function (without arguments) and use its return value as the default for this field."

In your working code:

@dataclass
class test:
    timestamp: datetime = field(default_factory=datetime.utcnow)

Notice we pass datetime.utcnow (the function itself) instead of datetime.utcnow() (the result of calling the function). The dataclass will invoke this function each time you create a test instance, giving you a fresh timestamp every time.

A quick analogy with regular classes

If you were writing a regular class without dataclasses, you wouldn't do this:

class Test:
    def __init__(self, timestamp=datetime.utcnow()):
        self.timestamp = timestamp

You'd instead write something like this to get a fresh timestamp per instance:

class Test:
    def __init__(self, timestamp=None):
        if timestamp is None:
            timestamp = datetime.utcnow()
        self.timestamp = timestamp

default_factory is just the dataclass way of handling this pattern cleanly and concisely.

To sum up

  • Python evaluates default values (for class fields and function parameters) once at definition time, not at instantiation/call time.
  • field(default_factory) lets you defer the creation of the default value until an instance is created, by passing a function that generates the value dynamically.

内容的提问来源于stack exchange,提问作者Niccola Tartaglia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 17:28:13