brei.construct

  1# ~/~ begin <<docs/utility.md#brei/construct.py>>[init]
  2import typing
  3from typing import Any, Self, Union, TypeVar, TypeGuard, Type, Optional, cast
  4import types
  5
  6import tomllib
  7import json
  8
  9from dataclasses import is_dataclass
 10from enum import Enum
 11from pathlib import Path
 12
 13from .errors import HelpfulUserError, InputError
 14
 15T = TypeVar("T")
 16
 17
 18def isgeneric(annot):
 19    return typing.get_origin(annot) and hasattr(annot, "__args__")
 20
 21
 22class FromStr:
 23    @classmethod
 24    def from_str(cls, _: str) -> Self:
 25        raise NotImplementedError()
 26
 27
 28def construct(annot: Any, json: Any) -> Any:
 29    try:
 30        return _construct(annot, json)
 31    except (AssertionError, ValueError) as e:
 32        raise InputError(annot, json) from e
 33
 34
 35def is_object_type(dtype: Type[Any]) -> TypeGuard[Type[dict[str, Any]]]:
 36    return (
 37        isgeneric(dtype)
 38        and typing.get_origin(dtype) is dict
 39        and typing.get_args(dtype)[0] is str
 40    )
 41
 42
 43def is_optional_type(dtype: Type[Any]) -> TypeGuard[Type[Optional[Any]]]:
 44    return (
 45        isgeneric(dtype)
 46        and typing.get_origin(dtype) is Union
 47        and typing.get_args(dtype)[1] is types.NoneType
 48    )
 49
 50
 51def _construct(annot: Type[T], json: Any) -> T:
 52    """Construct an object from a given type from a JSON stream.
 53
 54    The `annot` type should be one of: str, int, list[T], Optional[T],
 55    or a dataclass, and the JSON data should match exactly the given
 56    definitions in the dataclass hierarchy.
 57    """
 58    if annot is bool:
 59        assert isinstance(json, bool)
 60        return cast(T, json)
 61    if annot is str:
 62        assert isinstance(json, str)
 63        return cast(T, json)
 64    if annot is int:
 65        assert isinstance(json, int)
 66        return cast(T, json)
 67    if is_object_type(annot):
 68        assert isinstance(json, dict)
 69        return cast(
 70            T, {k: construct(typing.get_args(annot)[1], v) for k, v in json.items()}
 71        )
 72    if annot is Any:
 73        return cast(T, json)
 74    # if annot is dict or isgeneric(annot) and typing.get_origin(annot) is dict:
 75    #    assert isinstance(json, dict)
 76    #    return json
 77    if annot is Path and isinstance(json, str):
 78        return cast(T, Path(json))
 79    if isgeneric(annot) and typing.get_origin(annot) is list:
 80        assert isinstance(json, list)
 81        return cast(T, [construct(typing.get_args(annot)[0], item) for item in json])
 82    if is_optional_type(annot):
 83        if json is None:
 84            return cast(T, None)
 85        else:
 86            return cast(T, construct(typing.get_args(annot)[0], json))
 87    if isgeneric(annot) and typing.get_origin(annot) is types.UnionType:
 88        for dtype in typing.get_args(annot):
 89            try:
 90                return cast(T, _construct(dtype, json))
 91            except ValueError:
 92                continue
 93            except AssertionError:
 94                continue
 95        raise ValueError("None of the choices in type union match data.")
 96    if type(annot) is type and issubclass(annot, FromStr) and isinstance(json, str):
 97        return cast(T, annot.from_str(json))
 98    if is_dataclass(annot):
 99        assert isinstance(json, dict)
100        arg_annot = typing.get_type_hints(annot)
101        # assert all(k in json for k in arg_annot)
102        args = {k: construct(arg_annot[k], json[k]) for k in json}
103        return cast(T, annot(**args))
104    if isinstance(json, str) and isinstance(annot, type) and issubclass(annot, Enum):
105        options = {opt.name.lower(): opt for opt in annot}
106        assert json.lower() in options
107        return cast(T, options[json.lower()])
108    raise ValueError(f"Couldn't construct {annot} from {repr(json)}")
109
110
111def read_from_file(data_type: Type[T], path: Path, section: Optional[str] = None) -> T:
112    """Read a config from given `path` in given `section`. The path should refer to
113    a TOML or JSON file that should decode to a `Config` object. If `section` is given, only
114    that section is decoded to a `Config` object. The `section` string may contain
115    periods to indicate deeper nesting.
116
117    Example:
118
119    ```python
120    read_from_file(Config, Path("./pyproject.toml"), "tool.loom")
121    ```
122    """
123    if not path.exists():
124        raise HelpfulUserError(f"File not found: {path}")
125    with open(path, "rb") as f:
126        if path.suffix == ".toml":
127            data: Any = tomllib.load(f)
128        elif path.suffix == ".json":
129            data = json.load(f)
130        else:
131            raise HelpfulUserError(f"Unrecognized file format: {path}")
132
133    try:
134        if section is not None:
135            for s in section.split("."):
136                data = data[s]
137    except KeyError as e:
138        raise HelpfulUserError(
139            f"Data file `{path}` should contain section `{section}`."
140        ) from e
141
142    return construct(data_type, data)
143# ~/~ end
def isgeneric(annot):
19def isgeneric(annot):
20    return typing.get_origin(annot) and hasattr(annot, "__args__")
class FromStr:
23class FromStr:
24    @classmethod
25    def from_str(cls, _: str) -> Self:
26        raise NotImplementedError()
@classmethod
def from_str(cls, _: str) -> Self:
24    @classmethod
25    def from_str(cls, _: str) -> Self:
26        raise NotImplementedError()
def construct(annot: Any, json: Any) -> Any:
29def construct(annot: Any, json: Any) -> Any:
30    try:
31        return _construct(annot, json)
32    except (AssertionError, ValueError) as e:
33        raise InputError(annot, json) from e
def is_object_type(dtype: Type[Any]) -> TypeGuard[Type[dict[str, Any]]]:
36def is_object_type(dtype: Type[Any]) -> TypeGuard[Type[dict[str, Any]]]:
37    return (
38        isgeneric(dtype)
39        and typing.get_origin(dtype) is dict
40        and typing.get_args(dtype)[0] is str
41    )
def is_optional_type(dtype: Type[Any]) -> TypeGuard[Type[Any | None]]:
44def is_optional_type(dtype: Type[Any]) -> TypeGuard[Type[Optional[Any]]]:
45    return (
46        isgeneric(dtype)
47        and typing.get_origin(dtype) is Union
48        and typing.get_args(dtype)[1] is types.NoneType
49    )
def read_from_file( data_type: Type[~T], path: pathlib.Path, section: str | None = None) -> ~T:
112def read_from_file(data_type: Type[T], path: Path, section: Optional[str] = None) -> T:
113    """Read a config from given `path` in given `section`. The path should refer to
114    a TOML or JSON file that should decode to a `Config` object. If `section` is given, only
115    that section is decoded to a `Config` object. The `section` string may contain
116    periods to indicate deeper nesting.
117
118    Example:
119
120    ```python
121    read_from_file(Config, Path("./pyproject.toml"), "tool.loom")
122    ```
123    """
124    if not path.exists():
125        raise HelpfulUserError(f"File not found: {path}")
126    with open(path, "rb") as f:
127        if path.suffix == ".toml":
128            data: Any = tomllib.load(f)
129        elif path.suffix == ".json":
130            data = json.load(f)
131        else:
132            raise HelpfulUserError(f"Unrecognized file format: {path}")
133
134    try:
135        if section is not None:
136            for s in section.split("."):
137                data = data[s]
138    except KeyError as e:
139        raise HelpfulUserError(
140            f"Data file `{path}` should contain section `{section}`."
141        ) from e
142
143    return construct(data_type, data)

Read a config from given path in given section. The path should refer to a TOML or JSON file that should decode to a Config object. If section is given, only that section is decoded to a Config object. The section string may contain periods to indicate deeper nesting.

Example:

read_from_file(Config, Path("./pyproject.toml"), "tool.loom")