From ef425840b6ae8edeed45fcd9472202e5f203c5f5 Mon Sep 17 00:00:00 2001 From: Richard Date: Mon, 5 Feb 2024 09:22:10 +0000 Subject: [PATCH] special case for serialising Path objects --- autoconf/dictable.py | 9 +++++++++ test_autoconf/test_dictable.py | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/autoconf/dictable.py b/autoconf/dictable.py index 8171b49..4259ca6 100644 --- a/autoconf/dictable.py +++ b/autoconf/dictable.py @@ -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", @@ -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) diff --git a/test_autoconf/test_dictable.py b/test_autoconf/test_dictable.py index e163ab8..10b9f25 100644 --- a/test_autoconf/test_dictable.py +++ b/test_autoconf/test_dictable.py @@ -2,6 +2,7 @@ import numpy as np import pytest +from pathlib import Path from autoconf.dictable import to_dict, from_dict, register_parser @@ -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