Skip to content

Commit af9fb12

Browse files
dcherianclaude
andcommitted
Memoize parse_cell_methods_attr
The string is typically shared across all variables in a dataset, so parse once per distinct attr. Wrap the cached result in `Frozen` to prevent accidental mutation of the shared value. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 9716f18 commit af9fb12

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

‎cf_xarray/utils.py‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
1+
import functools
12
import inspect
23
import os
34
import warnings
45
from collections import defaultdict
5-
from collections.abc import Iterable
6+
from collections.abc import Iterable, Mapping
67
from typing import Any
78
from xml.etree import ElementTree
89

910
import numpy as np
1011
from xarray import DataArray
12+
from xarray.core.utils import Frozen
1113

1214
try:
1315
import cftime
@@ -64,25 +66,32 @@ def _is_datetime_like(da: DataArray) -> bool:
6466
return False
6567

6668

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]:
6871
"""
6972
Parse cell_methods attributes (format is 'measure: name').
7073
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+
7180
Parameters
7281
----------
7382
attr : str
7483
String to parse
7584
7685
Returns
7786
-------
78-
Dictionary mapping measure to name
87+
Read-only mapping from measure to name.
7988
"""
8089
strings = [s for scolons in attr.split(":") for s in scolons.split()]
8190
if len(strings) % 2 != 0:
8291
raise ValueError(f"attrs['cell_measures'] = {attr!r} is malformed.")
8392

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))
8695
)
8796

8897

0 commit comments

Comments
 (0)