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 eric.smith, mkurnikov
Date 2018-08-14.23:53:57
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1534290837.91.0.56676864532.issue34409@psf.upfronthosting.co.za>
In-reply-to
Content
from pprint import pprint
from typing import List, Any, Dict

import dataclasses
from dataclasses import field


def service_interface_dict_factory(obj: Any) -> Dict[str, Any]:
    print(type(obj)) # <- type(obj) here is a list, but there's no way to understand whether it's a ServiceInterface or
    # InputVar except for looking for the presence of certain keys which is not very convenient
    return dict(obj)


@dataclasses.dataclass
class InputVar(object):
    name: str
    required: bool = False
    options: Dict[str, Any] = field(default_factory=dict)


@dataclasses.dataclass
class ServiceInterface(object):
    input: List[InputVar] = field(default_factory=list)


if __name__ == '__main__':
    inputvar_inst = InputVar(name='myinput',
                             required=False,
                             options={'default': 'mytext'})
    interface = ServiceInterface(input=[inputvar_inst])

    outdict = dataclasses.asdict(interface, dict_factory=service_interface_dict_factory)
    print('outdict', end=' ')
    pprint(outdict)

    # prints:
    # outdict {'input': [{'name': 'myinput',
    #         'options': {'default': 'mytext'},
    #         'required': False}]}

    # desirable output
    # {'input': [{
    #     'name': 'myinput',
    #     'required': False,
    #     'default': 'mytext'
    # }]}
    # "default" key moved to the root of the dictionary (inside list)
History
Date User Action Args
2018-08-14 23:53:57mkurnikovsetrecipients: + mkurnikov, eric.smith
2018-08-14 23:53:57mkurnikovsetmessageid: <1534290837.91.0.56676864532.issue34409@psf.upfronthosting.co.za>
2018-08-14 23:53:57mkurnikovlinkissue34409 messages
2018-08-14 23:53:57mkurnikovcreate