Closed healthmatrice closed 1 year ago
if we use Tuple[int]
it give a different error:
@dataclass_json
@dataclass
class Person2:
y: Tuple[int]
print(Person2((1,)).to_json())
Person2.schema()
822 super().__init__(*args, **kwargs)
823 if not utils.is_collection(tuple_fields):
--> 824 raise ValueError(
825 "tuple_fields must be an iterable of Field classes or " "instances."
826 )
828 try:
829 self.tuple_fields = [
830 resolve_field_instance(cls_or_instance)
831 for cls_or_instance in tuple_fields
832 ]
ValueError: tuple_fields must be an iterable of Field classes or instances.
If we use Tuple[int, int, int , int]
, the error is:
821 def __init__(self, tuple_fields, *args, **kwargs):
--> 822 super().__init__(*args, **kwargs)
823 if not utils.is_collection(tuple_fields):
824 raise ValueError(
825 "tuple_fields must be an iterable of Field classes or " "instances."
826 )
TypeError: Field.__init__() takes 1 positional argument but 4 were given
It looks like the problem is in following lines:
args = [inner(a, {}) for a in getattr(type_, '__args__', []) if
a is not type(None)]
if _is_optional(type_):
options["allow_none"] = True
if origin in TYPES:
return TYPES[origin](*args, **options)
When the type_ is Tuple[int, int, int]
. We should use fields.Tuple((fields.Int, fields.Int ,fields.Int))
However, the args are [fields.Int, fields.Int ,fields.Int]
, thus the *args
give out fields.Tuple(fields.Int, fields.Int ,fields.Int)
which is wrong.
There actually some deeper incompatibility here of this code. Because we can have Tuple[int, ...]
for varied length. However, the inner() will give us args = [fields.Int, Ellipsis]
I doubt this can be handled by fields.Tuple at all.
Maybe mashmallow does not support varied length tuple at all.
The marshmallow-dataclass
library had a similar issue and it was solved there. See:
https://github.com/lovasoa/marshmallow_dataclass/issues/63
@deansg thanks for the heads up. So I was correct, mashmallow does have concept of varied length tuple. They simply treat it as marshmallow.fields.List and then do some tricks during deser. This is why they have to subclass it. Seems too much code.
actually included the Tuple[T, ...] fix
Description
If the dataclass contain list/tuple as field. The schema generation fails.
The output is:
It is the same as the https://github.com/lidatong/dataclasses-json/issues/398 But I think mine has far more detail.
Code snippet that reproduces the issue
Describe the results you expected
it should create schema without error
Python version you are using
Python 3.10.6
Environment description
dataclasses-json==0.5.9 marshmallow==3.19.0 marshmallow-enum==1.5.1 mypy-extensions==1.0.0 packaging==23.1 typing-inspect==0.9.0 typing_extensions==4.7.1