This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author mkurnikov
Recipients mkurnikov
Date 2018-08-14.23:11:20
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1534288280.15.0.56676864532.issue34409@psf.upfronthosting.co.za>
In-reply-to
Content
Suppose I have two dataclasses:

@dataclass
class NestedDataclass(object):
    name: str
    options: Dict[str, Any] = field(default_factory=dict)

@dataclass
class RootDataclass(object):
    nested_list: List[NestedDataclass]

I want a dict under the key "options" to be merged in the NestedDataclass dict in the dataclasses.asdict(root_dcls_instance). 

For that, according to docs, I need to specify dict_factory= for dataclasses.asdict() function. 

The problem is that, according to the implementation, when this function "meets" dataclass, there's no way to customize how result dict will be built. Dataclass itself is never passed to the function. 

    if _is_dataclass_instance(obj):
        result = []
        for f in fields(obj):
            value = _asdict_inner(getattr(obj, f.name), dict_factory)
            result.append((f.name, value))
        return dict_factory(result)

Yes, I can catch "result" obj (what I did in the end):

def root_dataclass_dict_factory(obj):
    if isinstance(obj, list):
        dataclass_dict = dict(obj)
        if 'options' in dataclass_dict:
            dataclass_dict.update(dataclass_dict.pop('options'))

    return dict(obj)

The problem is that type of the dataclass is lost for the list, and if by any chance later I'll have "options" key in the RootDataclass, there's no way for me to distinguish between them cleanly. 

Other solution is to iterate over the RootDataclass dictionary, follow the path to the NestedDataclass and change dictionary there, but it even uglier. 

Would be nice to be able to somehow hook into the field traversal of the dataclass instance.
History
Date User Action Args
2018-08-14 23:11:20mkurnikovsetrecipients: + mkurnikov
2018-08-14 23:11:20mkurnikovsetmessageid: <1534288280.15.0.56676864532.issue34409@psf.upfronthosting.co.za>
2018-08-14 23:11:20mkurnikovlinkissue34409 messages
2018-08-14 23:11:20mkurnikovcreate