Skip to content

Add function to construct TOML dictionary for dataclass instance #12

@mthuurne

Description

@mthuurne

The Binder.bind() method creates a dataclass instance from the data in TOML dictionary. It would be useful to support the opposite conversion as well, where we accept a dataclass instance and return the corresponding TOML dictionary.

We do support conversion from dataclass instance to textual TOML representation with format_template(), but in the case of parsing it turned out to be useful to support dictionary input in addition to textual input, so when generating TOML, it's probably also useful to support dictionary output in addition to textual output.

This could either be a standalone function or a method on an instanced Binder. I think it would be more efficient to use an instanced Binder in the implementation, both to avoid code duplication and to not do redundant checks on the data class definition. However, as we have a binder cache already, we could have a standalone function forward the request to an instanced binder, if that simplifies the interface.

Note that dataclasses.asdict() offers similar functionality, but it does not handle some conversions like timedelta, modules and dashes in key names. Perhaps we can use asdict() with a custom dictionary factory, but probably not, as there is no accompanying list factory.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions