我需要entries字段只有一个或两个元素的元组,但不能更多。但这样的设计会产生错误。
from decimal import Decimal as _Decimal
from dataclasses import field
from typing import Tuple
from typing import Union
import marshmallow
import marshmallow_dataclass
from marshmallow_dataclass import dataclass
from marshmallow_dataclass import NewType
Decimal = NewType("Decimal", _Decimal, field=marshmallow.fields.Decimal, as_string=True)
Entries = Union[Tuple[Decimal], Tuple[Decimal, Decimal]]
@dataclass(frozen=True)
class Signal(Model):
entries: Entries = field(default_factory=tuple)
...
@classmethod
@property
def Schema(cls):
return marshmallow_dataclass.class_schema(cls)
class Meta:
ordered = True错误消息
super().__init__(*args, **kwargs)
File "/home/prefixet/.local/share/virtualenvs/telegram-bot-LL7aNOup/lib/python3.8/site-packages/marshmallow/fields.py", line 185, in __init__
raise ValueError("'missing' must not be set for required fields.")
ValueError: 'missing' must not be set for required fields.
Process finished with exit code 1另外,我尝试使用TupleDecimal,但是它不起作用。谢谢。
发布于 2021-06-04 22:31:58
当您提出问题时,情况可能并非如此,但目前marshmallow-dataclass有一个Union扩展。
pip install "marshmallow-dataclass[enum,union]"将同时安装该扩展和枚举扩展(不确定如何只安装其中一个)。
https://github.com/lovasoa/marshmallow_dataclass#installation
发布于 2020-04-07 15:37:11
如果我删除默认工厂,它就可以工作了:
@dataclass(frozen=True)
class Signal(Model):
entries: Entries = field()霍普这是救命啊。
https://stackoverflow.com/questions/61064193
复制相似问题