konradhalas / dacite

Simple creation of data classes from dictionaries.
MIT License
1.72k stars 106 forks source link

Tuple type (only first) processed #178

Closed plandes closed 1 year ago

plandes commented 2 years ago

Data classes with fields of type List[Whatever] work fine, but not with Tuple[Watever]. Only the first element gets process properly in to a instance of the contained type. However, the rest don't and then it (as it should) fail on the type check.

Example:

#!/usr/bin/env python

from typing import Tuple, List
from dataclasses import dataclass
from dacite import from_dict

@dataclass
class Person(object):
    name: str
    age: int

@dataclass
class Department(object):
    name: str
    employees: List[Person]

@dataclass
class DepartmentWithTuple(object):
    name: str
    employees: Tuple[Person]

data = {'name': 'hr',
        'employees': [{'name': 'bob', 'age': 21},
                      {'name': 'jill', 'age': 25}]}
print(from_dict(data_class=Department, data=data))

data = {'name': 'hr',
        'employees': ({'name': 'bob', 'age': 21},
                      {'name': 'jill', 'age': 25})}
print(from_dict(data_class=DepartmentWithTuple, data=data))

Yields:

Department(name='hr', employees=[Person(name='bob', age=21), Person(name='jill', age=25)])
Traceback (most recent call last):
  File "/w/yamlinst/ex.py", line 35, in <module>
    print(from_dict(data_class=DepartmentWithTuple, data=data))
  File "/Users/landes/opt/lib/python-3.9.9/lib/python3.9/site-packages/dacite/core.py", line 68, in from_dict
    raise WrongTypeError(field_path=field.name, field_type=field.type, value=value)
dacite.exceptions.WrongTypeError: wrong value type for field "employees" - should be "typing.Tuple[__main__.Person]" instead of value "(Person(name='bob', age=21), {'name': 'jill', 'age': 25})" of type "tuple"
konradhalas commented 1 year ago

Your typing is wrong - should be Tuple[Person, ...] instead of Tuple[Person] - it means a tuple with only one element of the type Person.

plandes commented 1 year ago

@konradhalas Thank you for your response. This is helpful.