MikeWooster / jsonmarshal

marshal json to/from dataclasses
MIT License
5 stars 1 forks source link

Cannot unmarshal inherited dataclass #10

Open nschrader opened 3 years ago

nschrader commented 3 years ago

First things first: thank you for this great package!

@dataclass 
   ...: class XXX: 
   ...:     a: int 
   ...:                                                                         

In [4]: marshal(XXX(a=1))                                                       
Out[4]: {'a': 1}

In [5]: x = marshal(XXX(a=1))                                                   

In [6]: unmarshal(x, XXX)                                                       
Out[6]: XXX(a=1)

In [7]: @dataclass 
   ...: class YYY(XXX): 
   ...:     b: int 
   ...:                                                                         

In [8]: x = marshal(YYY(a=1, b=2))                                              

In [9]: x                                                                       
Out[9]: {'a': 1, 'b': 2}

In [10]: unmarshal(x, YYY)                                                      
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-10-dc946d818557> in <module>
----> 1 unmarshal(x, YYY)

~/.local/lib/python3.8/site-packages/jsonmarshal/unmarshal.py in unmarshal(response, schema, datetime_fmt, date_fmt)
     40     """
     41     unmarshaller = _Unmarshaller(response, schema, datetime_fmt, date_fmt)
---> 42     return unmarshaller.unmarshal()
     43 
     44 

~/.local/lib/python3.8/site-packages/jsonmarshal/unmarshal.py in unmarshal(self)
    126 
    127             processor = self.processors[item.schema_type]
--> 128             processor(item)
    129 
    130             self.promote()

~/.local/lib/python3.8/site-packages/jsonmarshal/unmarshal.py in process_dict(self, item)
    170         if not item.cleaned:
    171             # Go through each known field and fix the keys in the original dictionary
--> 172             item = self.clean_item(item)
    173 
    174         if not self.dump and item.unmarshalled is False:

~/.local/lib/python3.8/site-packages/jsonmarshal/unmarshal.py in clean_item(self, item)
    205 
    206         for data_key, v in item.data.items():
--> 207             schema_type = item.schema.__annotations__[data_key]
    208             child = _ResultContainer(
    209                 data=v,

KeyError: 'a'

So it's possible to marshal an inherited dataclass, but not to unmarshal it.

reynoldsm88 commented 1 year ago

I have also run into this same issue... was wondering if you found a fix @nschrader ?