From b76a624b4f6408e27739afff464216f57d4e3603 Mon Sep 17 00:00:00 2001 From: Hykilpikonna Date: Mon, 15 Aug 2022 20:05:38 -0400 Subject: [PATCH] [+] Add simple namespace support --- hypy_utils/__init__.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/hypy_utils/__init__.py b/hypy_utils/__init__.py index a64cc74..721dca7 100644 --- a/hypy_utils/__init__.py +++ b/hypy_utils/__init__.py @@ -9,6 +9,7 @@ import time from datetime import datetime, date from pathlib import Path from typing import Union, Callable +from types import SimpleNamespace def ansi_rgb(r: int, g: int, b: int, foreground: bool = True) -> str: @@ -111,6 +112,10 @@ class EnhancedJSONEncoder(json.JSONEncoder): # https://stackoverflow.com/a/51286749/7346633 if dataclasses.is_dataclass(o): return dataclasses.asdict(o) + + # Simple namespace + if isinstance(o, SimpleNamespace): + return o.__dict__ # Support encoding datetime if isinstance(o, (datetime, date)): @@ -139,6 +144,10 @@ def json_stringify(obj: object, indent: Union[int, None] = None) -> str: return json.dumps(obj, indent=indent, cls=EnhancedJSONEncoder, ensure_ascii=False) +def jsn(s: str): + return json.loads(s, object_hook=lambda d: SimpleNamespace(**d)) + + def write(file: Union[str, Path], text: str) -> None: """ Write text to a file