|
| 1 | +""" |
| 2 | +Started from xarray options.py |
| 3 | +""" |
| 4 | + |
| 5 | +import copy |
| 6 | +from typing import Any, MutableMapping |
| 7 | + |
| 8 | +from .utils import always_iterable |
| 9 | + |
| 10 | +OPTIONS: MutableMapping[str, Any] = { |
| 11 | + "custom_criteria": [], |
| 12 | +} |
| 13 | + |
| 14 | + |
| 15 | +class set_options: |
| 16 | + """Set options for cf-xarray in a controlled context. |
| 17 | + Currently supported options: |
| 18 | + - ``custom_critera``: Translate from axis, coord, or custom name to |
| 19 | + variable name optionally using ``custom_criteria``. Default: []. |
| 20 | +
|
| 21 | + You can use ``set_options`` either as a context manager: |
| 22 | + >>> my_custom_criteria = { 'ssh': {'name': 'elev$'} } |
| 23 | + >>> ds = xr.Dataset({"elev": np.arange(1000)}) |
| 24 | + >>> with cf_xarray.set_options(custom_criteria=my_custom_criteria): |
| 25 | + ... assert (ds['elev'] == ds.cf['ssh']).all() |
| 26 | +
|
| 27 | + Or to set global options: |
| 28 | + >>> cf_xarray.set_options(custom_criteria=my_custom_criteria) |
| 29 | + >>> assert (ds['elev'] == ds.cf['ssh']).all() |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__(self, **kwargs): |
| 33 | + self.old = {} |
| 34 | + for k, v in kwargs.items(): |
| 35 | + if k not in OPTIONS: |
| 36 | + raise ValueError( |
| 37 | + f"argument name {k!r} is not in the set of valid options {set(OPTIONS)!r}" |
| 38 | + ) |
| 39 | + self.old[k] = OPTIONS[k] |
| 40 | + self._apply_update(kwargs) |
| 41 | + |
| 42 | + def _apply_update(self, options_dict): |
| 43 | + options_dict = copy.deepcopy(options_dict) |
| 44 | + for k, v in options_dict.items(): |
| 45 | + if k == "custom_criteria": |
| 46 | + options_dict["custom_criteria"] = always_iterable( |
| 47 | + options_dict["custom_criteria"], allowed=(tuple, list) |
| 48 | + ) |
| 49 | + OPTIONS.update(options_dict) |
| 50 | + |
| 51 | + def __enter__(self): |
| 52 | + return |
| 53 | + |
| 54 | + def __exit__(self, type, value, traceback): |
| 55 | + self._apply_update(self.old) |
0 commit comments