|
| 1 | +import functools |
1 | 2 | import inspect |
2 | 3 | import os |
3 | 4 | import warnings |
4 | 5 | from collections import defaultdict |
5 | | -from collections.abc import Iterable |
| 6 | +from collections.abc import Iterable, Mapping |
6 | 7 | from typing import Any |
7 | 8 | from xml.etree import ElementTree |
8 | 9 |
|
9 | 10 | import numpy as np |
10 | 11 | from xarray import DataArray |
| 12 | +from xarray.core.utils import Frozen |
11 | 13 |
|
12 | 14 | try: |
13 | 15 | import cftime |
@@ -64,25 +66,32 @@ def _is_datetime_like(da: DataArray) -> bool: |
64 | 66 | return False |
65 | 67 |
|
66 | 68 |
|
67 | | -def parse_cell_methods_attr(attr: str) -> dict[str, str]: |
| 69 | +@functools.lru_cache(maxsize=256) |
| 70 | +def parse_cell_methods_attr(attr: str) -> Mapping[str, str]: |
68 | 71 | """ |
69 | 72 | Parse cell_methods attributes (format is 'measure: name'). |
70 | 73 |
|
| 74 | + The result is memoized per attribute string and returned as a read-only |
| 75 | + ``Frozen`` mapping. ``cell_measures`` strings are typically shared across |
| 76 | + many variables in a dataset (e.g., every CMIP variable carries the same |
| 77 | + ``area: areacella volume: ...``), so parsing once and reusing avoids |
| 78 | + repeated string splitting in the hot path of ``_get_measure``. |
| 79 | +
|
71 | 80 | Parameters |
72 | 81 | ---------- |
73 | 82 | attr : str |
74 | 83 | String to parse |
75 | 84 |
|
76 | 85 | Returns |
77 | 86 | ------- |
78 | | - Dictionary mapping measure to name |
| 87 | + Read-only mapping from measure to name. |
79 | 88 | """ |
80 | 89 | strings = [s for scolons in attr.split(":") for s in scolons.split()] |
81 | 90 | if len(strings) % 2 != 0: |
82 | 91 | raise ValueError(f"attrs['cell_measures'] = {attr!r} is malformed.") |
83 | 92 |
|
84 | | - return dict( |
85 | | - zip(strings[slice(0, None, 2)], strings[slice(1, None, 2)], strict=False) |
| 93 | + return Frozen( |
| 94 | + dict(zip(strings[slice(0, None, 2)], strings[slice(1, None, 2)], strict=False)) |
86 | 95 | ) |
87 | 96 |
|
88 | 97 |
|
|
0 commit comments