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

如何在Factory Boy的build方法中使用变量指定参数?

问题:使用factory_boy时通过变量指定参数报错的解决办法

正常运行的代码示例

import factory
from dataclasses import dataclass

@dataclass
class Note:
    write: bool
    read: bool

class NoteFactory(factory.Factory):
    class Meta:
        model = Note

    write = False
    read = False

note = NoteFactory.build(write=True)
print(note.write)

输出:True

报错场景

当尝试用变量指定参数时,代码触发错误:

var_write = 'write'
note = NoteFactory.build(var_write=True)
print(note.var_write)

输出:Note.__init__() got an unexpected keyword argument 'var_write'

解决办法

问题根源是直接把变量名当成了关键字参数名,Python会将var_write识别为参数名,而非它存储的字符串'write'。解决方式是用字典解包传递动态参数:

  1. 先构建一个字典,以变量存储的字符串为键,对应值为参数值
  2. 用**操作符将字典解包为关键字参数传入build()方法

修改后的代码:

var_write = 'write'
params = {var_write: True}
note = NoteFactory.build(**params)
print(note.write)

输出:True

这样就能正确将write参数设为True,避免参数名不匹配的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:34:54