skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    It's working if i remove default factory:

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

    Hope, it's help someone.


  2. This may not have been the case when you asked your question, but currently marshmallow-dataclass has a Union extension.

    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).

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search