Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for CustomCode-Types? #76

Open
carstencodes opened this issue Apr 8, 2020 · 0 comments
Open

Support for CustomCode-Types? #76

carstencodes opened this issue Apr 8, 2020 · 0 comments

Comments

@carstencodes
Copy link

Hi,

I'm using the library for quite a while and it is really cool. Unfortunately, I do have a project now which uses Enums and dataclasses.

The following code describes briefly what I'm doing:

from enum import Enum, auto
from dataclasses import dataclass, field, asdict
from dicttoxml import dicttoxml

class MyEnum:
    A = auto()
    B = auto()
    C = auto()

@dataclass
class MyDc
    x: str = field()
    y: int = field()
    z: MyEnum = field()

dc = MyDc()
dt = asdict(dc)
xml = dicttoxml(dt)

Creating a json file from the dictionary is possible, when using a customized JSONEncoder instance, which is handed over to the encode function.

With this issue I suggest the extension of the dicttoxml method:

def dicttoxml(obj, root=True, custom_root='root', ids=False, attr_type=True,
    item_func=default_item_func, cdata=False, *, converter_func=convert)

This way, a custom converter function can be used to serialize custom data types like Enums or special objects:

def convert_with_enum(obj, ids, attr_type, item_func, cdata, parent='root'):
    if isinstance(obj, Enum):
          item_name = item_func(parent)
          return convert_kv(item_name, obj.name, attr_type, cdata)
    return convert(obj, ids, attr_type, item_func, cdata, parent)

I can submit a pull request, if you consider this issue as valueable.

Regards Carsten

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant