I am using dataclasses + dataclasses_json to implement my web api.
My application will decode the request from dict to object, I hope that the object can still be generated without every field is fill, and fill the empty filed with default value.
This is my likely code:
from dataclasses import dataclass
from dataclasses_json import dataclass_json
@dataclass
class Glasses:
color: str
size: str
prize: int
@dataclass
class Tshirt:
color: str
size: str
prize: int
@dataclass_json
@dataclass
class People:
Name : str = 'James'
Age : int = 25
Glasses: Glasses = Glasses('black', 'M', 2500)
Tshirt: Tshirt = Tshirt('black', 'XL', 500)
p = {
'Name': 'Gino',
'Age': 20,
'Glasses': {
'color' : 'red',
'size' : 'M',
'prize' : 4000
},
'Tshirt': {
'color' : 'red',
'size' : 'M',
'prize' : 4000
}
}
a = People.from_dict(p)
print(a)
and I will get the error
Traceback (most recent call last):
File ".\People.py", line 39, in <module>
a = People.from_dict(p)
File "C:\Python3.7\lib\site-packages\dataclasses_json\api.py", line 83, in from_dict
return _decode_dataclass(cls, kvs, infer_missing)
File "C:\Python3.7\lib\site-packages\dataclasses_json\core.py", line 133, in _decode_dataclass
overrides = _user_overrides_or_exts(cls)
File "C:\Python3.7\lib\site-packages\dataclasses_json\core.py", line 59, in _user_overrides_or_exts
if field.type in encoders:
TypeError: unhashable type: 'Glasses'
I found that I can add (eq=True, frozen=True) So I change my code to
from dataclasses import dataclass
from dataclasses_json import dataclass_json
@dataclass(eq=True, frozen=True)
class Glasses:
color: str
size: str
prize: int
@dataclass(eq=True, frozen=True)
class Tshirt:
color: str
size: str
prize: int
@dataclass_json
@dataclass
class People:
Name : str = 'James'
Age : int = 25
Glasses: Glasses = Glasses('black', 'M', 2500)
Tshirt: Tshirt = Tshirt('black', 'XL', 500)
p = {
'Name': 'Gino',
'Age': 20,
'Glasses': {
'color' : 'red',
'size' : 'M',
'prize' : 4000
},
'Tshirt': {
'color' : 'red',
'size' : 'M',
'prize' : 4000
}
}
a = People.from_dict(p)
print(a)
And I got the other error
File ".\People.py", line 39, in <module>
a = People.from_dict(p)
File "C:\Python3.7\lib\site-packages\dataclasses_json\api.py", line 83, in from_dict
return _decode_dataclass(cls, kvs, infer_missing)
File "C:\Python3.7\lib\site-packages\dataclasses_json\core.py", line 198, in _decode_dataclass
infer_missing)
File "C:\Python3.7\lib\site-packages\dataclasses_json\core.py", line 131, in _decode_dataclass
if isinstance(kvs, cls):
TypeError: isinstance() arg 2 must be a type or tuple of types
Is there any possible way to fit my requirement using built-in functions without coding it myself?