如何为recordclass dataobject的枚举属性设置默认值?
recordclass dataobject枚举字段默认值SyntaxError问题解决办法
在recordclass 0.17.5版本中,直接给dataobject的枚举类型字段设置默认值会触发SyntaxError——原因是库生成__new__方法时,会把枚举实例的repr结果直接写入参数默认值(比如color=<Color.RED: 1>),这不符合Python语法规范。以下是两种可行的解决办法:
方法一:通过__post_init__设置默认值
不在类定义时直接给字段赋值,而是在实例初始化完成后补全默认值:
from enum import Enum, auto from recordclass import dataobject class Color(Enum): RED = auto() BLUE = auto() class Point(dataobject): x: float y: float color: Color def __post_init__(self): # 仅当未传入color参数时设置默认值 if self.color is None: self.color = Color.RED # 测试用例 pt_with_default = Point(1, 2) print(pt_with_default) # 输出: Point(x=1, y=2, color=<Color.RED: 1>) pt_with_custom = Point(3, 4, Color.BLUE) print(pt_with_custom) # 输出: Point(x=3, y=4, color=<Color.BLUE: 2>)
方法二:使用field的default_factory
借助recordclass提供的field工具,通过工厂函数生成默认值,避免直接将枚举实例写入参数默认值:
from enum import Enum, auto from recordclass import dataobject, field class Color(Enum): RED = auto() BLUE = auto() class Point(dataobject): x: float y: float color: Color = field(default_factory=lambda: Color.RED) # 测试用例 pt_with_default = Point(1, 2) print(pt_with_default) # 输出: Point(x=1, y=2, color=<Color.RED: 1>) pt_with_custom = Point(3, 4, Color.BLUE) print(pt_with_custom) # 输出: Point(x=3, y=4, color=<Color.BLUE: 2>)
这两种方法都能绕开recordclass的语法生成bug,实现枚举字段默认值的需求。
内容的提问来源于stack exchange,提问作者Andrew Eckart
相关产品推荐
相关产品推荐

