Skip to content

Commit c6c4b5d

Browse files
committed
Compile regexes
1 parent fd7e486 commit c6c4b5d

File tree

2 files changed

+11
-12
lines changed

2 files changed

+11
-12
lines changed

cf_xarray/accessor.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1363,8 +1363,6 @@ def guess_coord_axis(self, verbose: bool = False) -> Union[DataArray, Dataset]:
13631363
-------
13641364
DataArray or Dataset with appropriate attributes added
13651365
"""
1366-
import re
1367-
13681366
obj = self._obj.copy(deep=True)
13691367
for var in obj.coords.variables:
13701368
if obj[var].ndim == 1 and _is_datetime_like(obj[var]):
@@ -1375,14 +1373,14 @@ def guess_coord_axis(self, verbose: bool = False) -> Union[DataArray, Dataset]:
13751373
obj[var].attrs = dict(ChainMap(obj[var].attrs, ATTRS["time"]))
13761374
continue # prevent second detection
13771375

1378-
for axis, pattern in regex.items():
1376+
for name, pattern in regex.items():
13791377
# match variable names
1380-
if re.match(pattern, var.lower()):
1378+
if pattern.match(var.lower()):
13811379
if verbose:
13821380
print(
1383-
f"I think {var!r} is of type {axis!r}. It matched {pattern!r}"
1381+
f"I think {var!r} is of type {name!r}. It matched {pattern!r}"
13841382
)
1385-
obj[var].attrs = dict(ChainMap(obj[var].attrs, ATTRS[axis]))
1383+
obj[var].attrs = dict(ChainMap(obj[var].attrs, ATTRS[name]))
13861384
return obj
13871385

13881386
def drop(self, *args, **kwargs):

cf_xarray/criteria.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"""
66

77

8+
import re
89
from typing import MutableMapping, Tuple
910

1011
coordinate_criteria: MutableMapping[str, MutableMapping[str, Tuple]] = {
@@ -77,15 +78,15 @@
7778

7879
#: regular expressions for guess_coord_axis
7980
regex = {
80-
"time": "\\bt\\b|(time|min|hour|day|week|month|year)[0-9]*",
81-
"vertical": (
81+
"time": re.compile("\\bt\\b|(time|min|hour|day|week|month|year)[0-9]*"),
82+
"vertical": re.compile(
8283
"(z|nav_lev|gdep|lv_|bottom_top|sigma|h(ei)?ght|altitude|depth|"
8384
"isobaric|pres|isotherm)[a-z_]*[0-9]*"
8485
),
85-
"Y": "y",
86-
"latitude": "y?(nav_lat|lat|gphi)[a-z0-9]*",
87-
"X": "x",
88-
"longitude": "x?(nav_lon|lon|glam)[a-z0-9]*",
86+
"Y": re.compile("y"),
87+
"latitude": re.compile("y?(nav_lat|lat|gphi)[a-z0-9]*"),
88+
"X": re.compile("x"),
89+
"longitude": re.compile("x?(nav_lon|lon|glam)[a-z0-9]*"),
8990
}
9091
regex["Z"] = regex["vertical"]
9192
regex["T"] = regex["time"]

0 commit comments

Comments
 (0)