|
| 1 | +"""Module for utilities which help to create custom DataArray classes. |
| 2 | +
|
| 3 | +Currently this module provides only ``include`` class decorator |
| 4 | +which can include a custom DataArray definition written in a file. |
| 5 | +
|
| 6 | +""" |
| 7 | +__all__ = ["include"] |
| 8 | + |
| 9 | + |
| 10 | +# standard library |
| 11 | +import json |
| 12 | +import re |
| 13 | +from pathlib import Path |
| 14 | +from typing import Any, Callable, Dict, Union |
| 15 | + |
| 16 | + |
| 17 | +# dependencies |
| 18 | +import toml |
| 19 | +import yaml |
| 20 | +from .dataclasses import ctype |
| 21 | +from .ensuring import ensure_ctypes |
| 22 | + |
| 23 | + |
| 24 | +# constants |
| 25 | +ATTRS = "desc", "dims", "dtype" |
| 26 | +COORDS = "coords" |
| 27 | +DEFAULT = "default" |
| 28 | +JSON_RE = r"\.json$" |
| 29 | +TOML_RE = r"\.toml$" |
| 30 | +YAML_RE = r"\.ya?ml$" |
| 31 | + |
| 32 | + |
| 33 | +# main functions |
| 34 | +def include(path: Union[Path, str]) -> Callable: |
| 35 | + """Class decorator to include a custom DataArray definition in a file. |
| 36 | +
|
| 37 | + File format of either JSON, TOML, or YAML is accepted. |
| 38 | + The following ``key=value`` pairs can be included if available. |
| 39 | +
|
| 40 | + - ``dims=<array of string>``: Dimensions of the DataArray. |
| 41 | + - ``dtype=<string>``: Datatype of the DataArray. |
| 42 | + - ``desc=<string>``: Short description of the DataArray. |
| 43 | + - ``coords=<map of coord>``: Definition of coordinates (coords). |
| 44 | + Each coord is a map which can have the following ``key=value`` pairs. |
| 45 | +
|
| 46 | + - ``dims=<array of string>``: Dimensions of a coordinate. |
| 47 | + - ``dtype=<string>``: Datatype of a coordinate. |
| 48 | + - ``desc=<string>``: Short description of a coordinate. |
| 49 | + - ``default=<any>``: Default value of a coordinate. |
| 50 | +
|
| 51 | + Args: |
| 52 | + path: Path or filename of the file. |
| 53 | +
|
| 54 | + Returns: |
| 55 | + decorator: Decorator to include the definition. |
| 56 | +
|
| 57 | + Examples: |
| 58 | + If a definition is written in ``dataarray.toml``:: |
| 59 | +
|
| 60 | + # dataarray.toml |
| 61 | +
|
| 62 | + dims = [ "x", "y" ] |
| 63 | + dtype = "float" |
| 64 | + desc = "DataArray class to represent images." |
| 65 | +
|
| 66 | + [coords.x] |
| 67 | + dims = "x" |
| 68 | + dtype = "int" |
| 69 | + default = 0 |
| 70 | +
|
| 71 | + [coords.y] |
| 72 | + dims = "y" |
| 73 | + dtype = "int" |
| 74 | + default = 0 |
| 75 | +
|
| 76 | + then the following two class definitions are equivalent:: |
| 77 | +
|
| 78 | + @dataarrayclass(accessor='img') |
| 79 | + @include('dataarray.toml') |
| 80 | + class Image: |
| 81 | + pass |
| 82 | +
|
| 83 | + :: |
| 84 | +
|
| 85 | + @dataarrayclass(accessor='img') |
| 86 | + class Image: |
| 87 | + \"\"\"DataArray class to represent images.\"\"\" |
| 88 | +
|
| 89 | + dims = 'x', 'y' |
| 90 | + dtype = float |
| 91 | + x: ctype('x', int) = 0 |
| 92 | + y: ctype('y', int) = 0 |
| 93 | +
|
| 94 | + """ |
| 95 | + path = Path(path).expanduser() |
| 96 | + loader = choose_loader_from(path) |
| 97 | + |
| 98 | + def decorator(cls: type) -> type: |
| 99 | + cls = ensure_ctypes(cls) |
| 100 | + |
| 101 | + config = loader(path) |
| 102 | + coords = config.get(COORDS, {}) |
| 103 | + |
| 104 | + for name in ATTRS: |
| 105 | + if name in config: |
| 106 | + setattr(cls, name, config[name]) |
| 107 | + |
| 108 | + for name, coord in coords.items(): |
| 109 | + cls.ctypes[name] = ctype(**coord) |
| 110 | + |
| 111 | + if DEFAULT in coord: |
| 112 | + setattr(cls, name, coord[DEFAULT]) |
| 113 | + |
| 114 | + return cls |
| 115 | + |
| 116 | + return decorator |
| 117 | + |
| 118 | + |
| 119 | +# helper functions |
| 120 | +def choose_loader_from(path: Path) -> Callable: |
| 121 | + """Choose file loader based on a filename.""" |
| 122 | + if re.search(JSON_RE, path.name): |
| 123 | + return load_json |
| 124 | + elif re.search(TOML_RE, path.name): |
| 125 | + return load_toml |
| 126 | + elif re.search(YAML_RE, path.name): |
| 127 | + return load_yaml |
| 128 | + else: |
| 129 | + raise ValueError("Invalid file format.") |
| 130 | + |
| 131 | + |
| 132 | +def load_json(path: Path) -> Dict[str, Any]: |
| 133 | + """Load a JSON file to create a dictionary.""" |
| 134 | + with path.open() as f: |
| 135 | + return json.load(f) |
| 136 | + |
| 137 | + |
| 138 | +def load_toml(path: Path) -> Dict[str, Any]: |
| 139 | + """Load a TOML file to create a dictionary.""" |
| 140 | + return toml.load(path) |
| 141 | + |
| 142 | + |
| 143 | +def load_yaml(path: Path) -> Dict[str, Any]: |
| 144 | + """Load a YAML file to create a dictionary.""" |
| 145 | + with path.open() as f: |
| 146 | + return yaml.load(f, Loader=yaml.SafeLoader) |
0 commit comments