Skip to content

Commit 3eb1b30

Browse files
committed
GMTDataArrayAccessor: Refactor the codes for the grid registration and gtype during initilization
1 parent 68a17a0 commit 3eb1b30

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed

pygmt/accessors.py

+11-14
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
GMT accessor for :class:`xarray.DataArray`.
33
"""
44

5+
import contextlib
56
from pathlib import Path
67

78
import xarray as xr
@@ -115,22 +116,18 @@ class GMTDataArrayAccessor:
115116

116117
def __init__(self, xarray_obj):
117118
self._obj = xarray_obj
118-
119-
self._source = self._obj.encoding.get("source")
120-
if self._source is not None and Path(self._source).exists():
121-
try:
122-
# Get grid registration and grid type from the last two columns
123-
# of the shortened summary information of `grdinfo`.
119+
# Default to Gridline registration and Cartensian grid type
120+
self._registration = 0
121+
self._gtype = 0
122+
123+
# If the source file exists, get grid registration and grid type from the last
124+
# two columns of the shortened summary information of `grdinfo`.
125+
_source = self._obj.encoding.get("source")
126+
if _source is not None and Path(self._source).exists():
127+
with contextlib.suppress(ValueError):
124128
self._registration, self._gtype = map(
125-
int, grdinfo(self._source, per_column="n").split()[-2:]
129+
int, grdinfo(_source, per_column="n").split()[-2:]
126130
)
127-
except ValueError:
128-
self._registration = 0 # Default to Gridline registration
129-
self._gtype = 0 # Default to Cartesian grid type
130-
else:
131-
self._registration = 0 # Default to Gridline registration
132-
self._gtype = 0 # Default to Cartesian grid type
133-
del self._source
134131

135132
@property
136133
def registration(self):

0 commit comments

Comments
 (0)