Skip to content

Commit

Permalink
special case for serialising Path objects
Browse files Browse the repository at this point in the history
  • Loading branch information
rhayes777 committed Feb 5, 2024
1 parent 0ee6ed4 commit ef42584
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
9 changes: 9 additions & 0 deletions autoconf/dictable.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ def to_dict(obj):
except Exception as e:
logger.info(e)

if isinstance(obj, Path):
return {
"type": "path",
"path": str(obj),
}

if inspect.isclass(obj):
return {
"type": "type",
Expand Down Expand Up @@ -177,6 +183,9 @@ def from_dict(dictionary, **kwargs):
logger.debug(e)
return None

if type_ == "path":
return Path(dictionary["path"])

if type_ in __parsers:
return __parsers[type_](dictionary, **kwargs)

Expand Down
7 changes: 7 additions & 0 deletions test_autoconf/test_dictable.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import numpy as np
import pytest
from pathlib import Path

from autoconf.dictable import to_dict, from_dict, register_parser

Expand Down Expand Up @@ -73,3 +74,9 @@ def test_register_parser():

def test_no_type():
assert from_dict({"hi": "there"}) == {"hi": "there"}


def test_serialise_path():
path = Path("/path/to/file.json")
path_dict = to_dict(path)
assert from_dict(path_dict) == path

0 comments on commit ef42584

Please sign in to comment.