pythontomltomlkit

Is it possible to teach TOML Kit how to dump an object?


I am generating TOML files with several tables using TOML Kit without any problem in general.

So far all the values were either strings or numbers, but today I first bumped into a problem. I was trying to dump a pathlib.Path object and it fails with a ConvertError Unable to convert an object of <class 'pathlib.WindowsPath'> to a TOML item. I fixed right away, adding a str in front, but I was thinking to do something valid in general.

Is there a way to teach TOML Kit how to convert a custom object to a valid TOML value? In the case of Path, would be extremely easy.


Solution

  • You want https://tomlkit.readthedocs.io/en/latest/api/#tomlkit.register_encoder

    Which you would use like this:

    from pathlib import Path
    from typing import Any
    
    import tomlkit
    from tomlkit.items import Item, String, ConvertError
    
    class PathItem(String):
        def unwrap(self) -> Path:
            return Path(super().unwrap())
    
    def path_encoder(obj: Any) -> Item:
        if isinstance(obj, Path):
            return PathItem.from_raw(str(obj))
        else:
            # we cannot convert this, but give other custom converters a
            # chance to run
            raise ConvertError
    
    tomlkit.register_encoder(path_encoder)
    
    obj = {'path': Path('/foo/bar')}
    document = tomlkit.dumps(obj)
    assert document == '''\
    path = "/foo/bar"
    '''