[英]Marshmallow dataclass not working with type hint Union
我需要條目字段只有一個或兩個元素的元組,但沒有更多。 但是這樣的設計會出錯。
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
另外,我嘗試使用元組 [十進制,...],但它不起作用。 謝謝。
如果我刪除默認工廠,它就可以工作:
@dataclass(frozen=True)
class Signal(Model):
entries: Entries = field()
希望,它可以幫助某人。
當您提出問題時,情況可能並非如此,但目前 marshmallow-dataclass 有一個 Union 擴展。
pip install "marshmallow-dataclass[enum,union]"
將安裝該擴展和枚舉擴展(不知道如何只獲得一個或另一個)。
https://github.com/lovasoa/marshmallow_dataclass#installation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.