【问题标题】:Marshmallow dataclass not working with type hint Union棉花糖数据类不使用类型提示联合
【发布时间】:2020-04-06 16:15:39
【问题描述】:

我需要条目字段只有一个或两个元素的元组,但没有更多。 但是这样的设计会出错。

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

另外,我尝试使用 Tuple[Decimal, ...],但它不起作用。 谢谢。

【问题讨论】:

    标签: python type-hinting marshmallow


    【解决方案1】:

    当您提出问题时,情况可能并非如此,但目前 marshmallow-dataclass 有一个 Union 扩展。

    pip install "marshmallow-dataclass[enum,union]" 将同时安装该扩展和枚举扩展(不确定如何获取其中一个)。

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

    【讨论】:

      【解决方案2】:

      如果我删除默认工厂,它就可以工作:

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

      希望对某人有所帮助。

      【讨论】:

        猜你喜欢
        • 2022-01-17
        • 2017-02-02
        • 2016-03-15
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 2015-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多