Python dataclasses.asdict 的复制边界:12 个测试看懂递归转换与共享引用

10-21 10阅读

给 dataclass 加一个“导出字典”按钮很容易:调用 asdict()。真正需要确认的是,导出过程中哪些对象被递归转换,哪些对象交给复制协议,原有的共享引用还在不在。它会生成新的 Python 数据结构,但不负责制定 JSON 格式,也不是只读取第一层字段的廉价操作。

本文用 12 项小规模测试回答这些问题。实测环境为 CPython 3.12.14,普通运行和 python -O 运行均通过。文档规则与固定版本的实现细节分开说明,不把单一版本观察写成所有 Python 实现的永久承诺。

Python dataclasses.asdict 的复制边界:12 个测试看懂递归转换与共享引用
独立模型生成的概念示意图,非真实软件截图。右侧表示递归重建的容器;下方 SHALLOW VIEW 指浅字段投影,仍引用原列表,并不代表会自动跟踪字段重新赋值的动态视图。

先选清楚你需要哪一种结果

  • 只要字段名和当前字段引用:使用 fields() 配合 getattr(),创建一层新的字典;不递归复制字段值。

  • 要把嵌套 dataclass 整理成字段映射:考虑 asdict(),但接受递归转换、复制协议以及引用关系可能改变的后果。

  • 要复制原对象图并保留类结构:考虑 deepcopy(),同时检查自定义复制规则;它不是 dataclass 转字典工具。

  • 要发给接口或持久化:先定义字段白名单、日期与特殊类型的编码规则,再选择序列化工具。asdict() 不会替你完成这套约定。

官方 asdict 文档明确列出递归处理的 dataclass、dict、list、tuple,并说明其他对象通过 deepcopy() 复制。下面的差别都来自这条处理边界,而不是函数名中的“dict”。

测试 01 至 02:浅投影与递归转换

测试 01 使用 slots=True 的 dataclass,直接从 fields() 枚举字段,因此不依赖实例拥有 __dict__。投影里的列表仍是原列表:原地 append 会被双方看到;把原字段重新赋值为另一个列表后,投影还指向旧列表。它是引用的浅层快照,不是自动更新的属性视图。

同一测试还说明,ClassVar 和 InitVar 不出现在 fields() 结果里,而 repr=False 的普通字段依然存在。repr=False 只控制生成的文本表示,不能当作导出时的隐私开关。字段范围可对照 fields() 文档核验。

测试 02 把 dataclass 分别放进 list 和 tuple,再放入 dict:嵌套 Leaf 变成字典,list 还是 list,tuple 还是 tuple,外层 dict 和列表也被重建。这与只复制最外层字典的浅拷贝有本质区别。

测试 03 至 05:值相等,不代表引用关系相同

测试 03 中,left 和 right 原本指向同一个列表。asdict() 得到两个内容相等、身份不同的列表;修改其中一个不会影响另一个。对同一个源对象执行一次 deepcopy(),得到的 Pair 仍然让两个字段共享同一份新列表。

原因要落在具体实现上:CPython v3.12.14 的 _asdict_inner逐个递归处理字段,并没有贯穿整次转换的 memo;遇到需要兜底复制的对象时,分别调用 deepcopy(obj)。而单次 deepcopy() 会使用 memo 记录已处理对象,详见 copy 文档。因此不能把 asdict() 当作“先对整个对象 deepcopy,再换一下外壳”。

测试 04 将同一个自定义 Token 放在两个字段中,统计 __deepcopy__ 的调用:asdict() 调用两次,deepcopy() 调用一次。钩子在本例中只计数并创建副本,真实类的钩子可能执行别的逻辑,也可能抛出异常。复制操作不是一个保证无副作用的读取动作。

测试 05 再加一层普通 Wrapper:Wrapper 走 deepcopy 路径,里面的 Leaf 仍是 Leaf,而不是字典。只有递归转换分支实际到达的 dataclass 才会被 asdict() 转换,不能把“递归”理解为遍历所有 Python 对象的全部属性。

也不要反向夸大为“asdict 的所有输出对象都与原对象不同”。该版本会直接返回部分原子类型;deepcopy 的规则与用户钩子也可以保留对象身份。本文测试 03 的“共享丢失”指示例中重建的列表,测试 04 指示例中被分别复制的普通对象,不是对所有类型的统一断言。

测试 06 至 08:namedtuple 与 dict_factory 的作用范围

测试 06 中,字段值是 namedtuple。实测得到的仍是同类型 Point,但内部 Leaf 已经变成字典,labels 列表也已重建。这是固定版本源码中的专门分支。它不同于直接调用 Point._asdict():后者创建字段名映射,并不会按 asdict 的规则递归转换其值。两种方法名称相近,不能混用。

测试 07 自定义 MadeDict 工厂:最外层 Box 和嵌套 Leaf 的转换结果都采用这个工厂,但中间原本存在的普通 dict 仍是普通 dict。因此,dict_factory 控制的是dataclass 转换得到的映射,不是一项“替换所有字典类型”的全局设置。这里工厂先处理子节点,再处理父节点,也是该实现与本例的实际调用顺序。

测试 08 把工厂写成永远返回空字典,仍然不能跳过字段复制。NoCopy.__deepcopy__ 先抛出 RuntimeError,工厂甚至还没有执行。要排除昂贵对象或不该导出的字段,应在递归和复制开始前挑选字段,而不是期待最后的 dict_factory 过滤器消除已经发生的工作。

这还影响性能判断:共享子结构可能被重复遍历,自定义复制钩子的成本也无法从字段数量推断。本文没有做速度或内存基准,不给“快几倍”“恒定开销”一类结论。

测试 09 至 12:循环、键与序列化错误

09 循环引用:一个 Box 指向自身,以及一个列表包含自身,在本版本 asdict() 下都触发 RecursionError。对这两个小对象图执行 deepcopy() 则保留了循环。测试只创建单节点循环,没有构造巨大链表、提高递归上限或开展资源压力测试。不要据此声称“所有包含循环的叶对象都必然失败”:某个普通对象进入 deepcopy 分支后,其内部循环可能由 deepcopy 自己处理。

10 字典键:frozen=True 的 Leaf 在本例中可哈希,能作为原字典的键;递归转换后却变成不可哈希的 dict,于是 asdict() 抛出 TypeError。它不只处理 dict 的值,也处理键。可用于 Python dict 的键,不一定能通过这一步转换,更不一定符合 JSON 对键的约束。

11 输入与字段状态:传入 dataclass 类本身或普通 dict 都会触发 TypeError,入口需要 dataclass 实例。另外,声明 init=False 又没有默认值、也未在其他地方初始化的字段,读取时可能触发 AttributeError。init=False 并不等于“导出时忽略”。测试只核验异常类型,不依赖可能随版本变化的错误文案。

12 JSON:date 字段经过 asdict() 后仍是 date,交给默认 json.dumps() 会抛出 TypeError;整数载荷则能成功编码。JSON 支持哪些类型由 JSONEncoder 的转换规则决定。遇到日期应明确选择 ISO 字符串或其他协议表示,而不是把“能打印出字典”当成“已经完成序列化”。

完整可运行代码

将下面整段保存为 asdict_boundaries.py,再分别运行 python asdict_boundaries.py 和 python -O asdict_boundaries.py。只依赖 Python 标准库。check() 显式抛出异常,未使用会被 -O 移除的 assert,因此优化模式也会真正执行所有核验。

from collections import namedtuple
from copy import deepcopy
from dataclasses import InitVar, asdict, dataclass, field, fields
from datetime import date
from typing import ClassVar
import json
import platform


def check(condition):
    if not condition:
        raise RuntimeError('check failed')


def expect_error(kind, action):
    try:
        action()
    except kind as exc:
        return type(exc).__name__
    raise RuntimeError(f'expected {kind.__name__}')


@dataclass
class Box:
    value: object


@dataclass
class Pair:
    left: object
    right: object


@dataclass(frozen=True)
class Leaf:
    n: int


def test_01():
    @dataclass(slots=True)
    class Record:
        values: list
        hidden: int = field(default=7, repr=False)
        seed: InitVar[int] = 0
        kind: ClassVar[str] = 'record'

    row = Record([1])
    shallow = {f.name: getattr(row, f.name) for f in fields(row)}
    check(list(shallow) == ['values', 'hidden'])
    check(shallow['values'] is row.values)
    row.values.append(2)
    row.values = [99]
    check(shallow['values'] == [1, 2])
    check(shallow['values'] is not row.values)
    print('01 shallow: mutation shared; rebinding not tracked; hidden included')


def test_02():
    src = Box({'items': [Leaf(1)], 'pair': (Leaf(2),)})
    out = asdict(src)
    check(out == {'value': {'items': [{'n': 1}], 'pair': ({'n': 2},)}})
    check(out['value'] is not src.value)
    check(out['value']['items'] is not src.value['items'])
    check(type(out['value']['pair']) is tuple)
    print('02 nested:', out)


def test_03():
    shared = [1]
    src = Pair(shared, shared)
    out, clone = asdict(src), deepcopy(src)
    check(out['left'] is not out['right'])
    check(out['left'] is not shared)
    check(clone.left is clone.right and clone.left is not shared)
    out['left'].append(2)
    check(out['right'] == [1] and shared == [1])
    print('03 alias: asdict=False; deepcopy=True; source unchanged')


def test_04():
    class Token:
        calls = 0

        def __deepcopy__(self, memo):
            type(self).calls += 1
            result = type(self)()
            memo[id(self)] = result
            return result

    token = Token()
    src = Pair(token, token)
    out = asdict(src)
    check(Token.calls == 2 and out['left'] is not out['right'])
    Token.calls = 0
    clone = deepcopy(src)
    check(Token.calls == 1 and clone.left is clone.right)
    print('04 custom leaf: asdict hook calls=2; deepcopy hook calls=1')


def test_05():
    class Wrapper:
        def __init__(self, child):
            self.child = child

    original = Wrapper(Leaf(3))
    out = asdict(Box(original))
    check(type(out['value']) is Wrapper)
    check(out['value'] is not original)
    check(type(out['value'].child) is Leaf)
    check(out['value'].child == Leaf(3))
    check(asdict(Box(Leaf(3))) == {'value': {'n': 3}})
    print('05 opaque wrapper: nested Leaf stays Leaf under deepcopy')


def test_06():
    Point = namedtuple('Point', 'child labels')
    point = Point(Leaf(4), ['x'])
    shallow = point._asdict()
    out = asdict(Box(point))['value']
    check(type(out) is Point and out.child == {'n': 4})
    check(out.labels == ['x'] and out.labels is not point.labels)
    check(shallow['child'] is point.child)
    check(shallow['labels'] is point.labels)
    print('06 namedtuple:', out)


def test_07():
    class MadeDict(dict):
        pass

    calls = []

    def factory(items):
        calls.append(tuple(name for name, value in items))
        return MadeDict(items)

    out = asdict(Box({'item': Leaf(5)}), dict_factory=factory)
    check(type(out) is MadeDict)
    check(type(out['value']) is dict)
    check(type(out['value']['item']) is MadeDict)
    check(calls == [('n',), ('value',)])
    print('07 factory:', calls, '; ordinary dict stays dict')


def test_08():
    class NoCopy:
        def __deepcopy__(self, memo):
            raise RuntimeError('copy blocked')

    calls = []

    def discard(items):
        calls.append('factory')
        return {}

    error = expect_error(
        RuntimeError,
        lambda: asdict(Box(NoCopy()), dict_factory=discard),
    )
    check(calls == [])
    print('08 factory cannot skip copying:', error, '; factory calls=0')


def test_09():
    node = Box(None)
    node.value = node
    cyclic_list = []
    cyclic_list.append(cyclic_list)
    first = expect_error(RecursionError, lambda: asdict(node))
    second = expect_error(RecursionError, lambda: asdict(Box(cyclic_list)))
    node_copy, list_copy = deepcopy(node), deepcopy(cyclic_list)
    check(node_copy is not node and node_copy.value is node_copy)
    check(list_copy is not cyclic_list and list_copy[0] is list_copy)
    print('09 cycles:', first, second, '; deepcopy preserves both cycles')


def test_10():
    src = Box({Leaf(6): 'ok'})
    error = expect_error(TypeError, lambda: asdict(src))
    check(src.value[Leaf(6)] == 'ok')
    print('10 dataclass dict key becomes unhashable:', error)


def test_11():
    @dataclass
    class Incomplete:
        missing: int = field(init=False)

    errors = [
        expect_error(TypeError, lambda: asdict(Box)),
        expect_error(TypeError, lambda: asdict({'value': 1})),
        expect_error(AttributeError, lambda: asdict(Incomplete())),
    ]
    print('11 invalid roots / missing field:', ', '.join(errors))


def test_12():
    out = asdict(Box(date(2026, 1, 2)))
    check(type(out['value']) is date)
    error = expect_error(TypeError, lambda: json.dumps(out))
    check(json.dumps(asdict(Box(7))) == '{"value": 7}')
    print('12 JSON: date remains date;', error, '; integer payload succeeds')


def main():
    print(f'Python {platform.python_version()} ({platform.python_implementation()})')
    tests = [
        test_01, test_02, test_03, test_04, test_05, test_06,
        test_07, test_08, test_09, test_10, test_11, test_12,
    ]
    for test in tests:
        test()
    print(f'PASS {len(tests)}/{len(tests)}')


if __name__ == '__main__':
    main()

精确输出

以下为 CPython 3.12.14 的实测输出,两种运行模式逐字一致;其他版本第一行会相应变化。PASS 12/12 只表示本文列出的测试全部通过,不是对所有类型的兼容性证明。

Python 3.12.14 (CPython)
01 shallow: mutation shared; rebinding not tracked; hidden included
02 nested: {'value': {'items': [{'n': 1}], 'pair': ({'n': 2},)}}
03 alias: asdict=False; deepcopy=True; source unchanged
04 custom leaf: asdict hook calls=2; deepcopy hook calls=1
05 opaque wrapper: nested Leaf stays Leaf under deepcopy
06 namedtuple: Point(child={'n': 4}, labels=['x'])
07 factory: [('n',), ('value',)] ; ordinary dict stays dict
08 factory cannot skip copying: RuntimeError ; factory calls=0
09 cycles: RecursionError RecursionError ; deepcopy preserves both cycles
10 dataclass dict key becomes unhashable: TypeError
11 invalid roots / missing field: TypeError, TypeError, AttributeError
12 JSON: date remains date; TypeError ; integer payload succeeds
PASS 12/12

在项目里使用前,确认这些边界

如果只需要日志中的几个字段,先白名单选择字段,再决定是否复制;如果需要完整的可交换数据格式,明确编码、解码以及版本兼容规则;如果业务依赖对象身份或共享引用,先画出对象图,再决定是否允许它们在导出时被拆开。

本文未覆盖任意容器子类、自定义映射协议、资源句柄、并发修改、深层大型结构,也没有验证其他解释器或其他 Python 版本。固定版本源码对 namedtuple、容器重建和原子类型的分支处理不应被扩展成“任何容器子类都兼容”的承诺。对于有复杂复制钩子或身份语义的业务对象,优先设计显式导出函数,并用自己的真实结构补充测试。

来源与版本说明

来源核验日期:2026 年 10 月 21 日(北京时间)。在线 /3.12 文档访问时页头显示 3.12.15;本文运行环境为 CPython 3.12.14,实现细节另外核对固定 v3.12.14 源码,并未宣称在 3.12.15 上运行过。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。