简体   繁体   English

棉花糖数据类不使用类型提示联合

[英]Marshmallow dataclass not working with type hint Union

I need the entries field to have only a Tuple of one or two elements, but no more.我需要条目字段只有一个或两个元素的元组,但没有更多。 But such a design gives an error.但是这样的设计会出错。

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

Error message错误信息

    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

Also, im trying use Tuple[Decimal, ...], but it's not working to.另外,我尝试使用元组 [十进制,...],但它不起作用。 Thanks.谢谢。

It's working if i remove default factory:如果我删除默认工厂,它就可以工作:

@dataclass(frozen=True)
class Signal(Model):
    entries: Entries = field()

Hope, it's help someone.希望,它可以帮助某人。

This may not have been the case when you asked your question, but currently marshmallow-dataclass has a Union extension.当您提出问题时,情况可能并非如此,但目前 marshmallow-dataclass 有一个 Union 扩展。

pip install "marshmallow-dataclass[enum,union]" will install both that extension and the enum extension (not sure how to get just one or the other). pip install "marshmallow-dataclass[enum,union]"将安装该扩展和枚举扩展(不知道如何只获得一个或另一个)。

https://github.com/lovasoa/marshmallow_dataclass#installation https://github.com/lovasoa/marshmallow_dataclass#installation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM