Skip to content

Commit 097e264

Browse files
author
Joseph Hamman
committed
stop using clever getattr hack
1 parent 6669035 commit 097e264

File tree

2 files changed

+32
-32
lines changed

2 files changed

+32
-32
lines changed

xarray/backends/common.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -509,15 +509,17 @@ def assert_open(self):
509509
class PickleByReconstructionWrapper(object):
510510

511511
def __init__(self, opener, file, mode='r', **kwargs):
512-
513512
self.opener = partial(opener, file, mode=mode, **kwargs)
514513
self.mode = mode
514+
self._ds = None
515515

516516
@property
517517
def value(self):
518-
return self.opener()
518+
self._ds = self.opener()
519+
return self._ds
519520

520521
def __getstate__(self):
522+
del self._ds
521523
state = self.__dict__.copy()
522524
if self.mode == 'w':
523525
# file has already been created, don't override when restoring
@@ -527,8 +529,5 @@ def __getstate__(self):
527529
def __setstate__(self, state):
528530
self.__dict__.update(state)
529531

530-
def __getitem__(self, key):
531-
return self.value[key]
532-
533-
def __getattr__(self, name):
534-
return getattr(self.value, name)
532+
def close(self):
533+
self._ds.close()

xarray/backends/rasterio_.py

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,15 @@
2525
class RasterioArrayWrapper(BackendArray):
2626
"""A wrapper around rasterio dataset objects"""
2727

28-
def __init__(self, rasterio_ds):
29-
self.rasterio_ds = rasterio_ds
30-
self._shape = (rasterio_ds.count, rasterio_ds.height,
31-
rasterio_ds.width)
28+
def __init__(self, riods):
29+
self.riods = riods
30+
self._shape = (riods.value.count, riods.value.height,
31+
riods.value.width)
3232
self._ndims = len(self.shape)
3333

3434
@property
3535
def dtype(self):
36-
dtypes = self.rasterio_ds.dtypes
36+
dtypes = self.riods.value.dtypes
3737
if not np.all(np.asarray(dtypes) == dtypes[0]):
3838
raise ValueError('All bands should have the same dtype')
3939
return np.dtype(dtypes[0])
@@ -105,7 +105,7 @@ def _get_indexer(self, key):
105105
def __getitem__(self, key):
106106
band_key, window, squeeze_axis, np_inds = self._get_indexer(key)
107107

108-
out = self.rasterio_ds.read(band_key, window=tuple(window))
108+
out = self.riods.value.read(band_key, window=tuple(window))
109109
if squeeze_axis:
110110
out = np.squeeze(out, axis=squeeze_axis)
111111
return indexing.NumpyIndexingAdapter(out)[np_inds]
@@ -203,20 +203,20 @@ def open_rasterio(filename, parse_coordinates=None, chunks=None, cache=None,
203203
coords = OrderedDict()
204204

205205
# Get bands
206-
if riods.count < 1:
206+
if riods.value.count < 1:
207207
raise ValueError('Unknown dims')
208-
coords['band'] = np.asarray(riods.indexes)
208+
coords['band'] = np.asarray(riods.value.indexes)
209209

210210
# Get coordinates
211211
if LooseVersion(rasterio.__version__) < '1.0':
212-
transform = riods.affine
212+
transform = riods.value.affine
213213
else:
214-
transform = riods.transform
214+
transform = riods.value.transform
215215
if transform.is_rectilinear:
216216
# 1d coordinates
217217
parse = True if parse_coordinates is None else parse_coordinates
218218
if parse:
219-
nx, ny = riods.width, riods.height
219+
nx, ny = riods.value.width, riods.value.height
220220
# xarray coordinates are pixel centered
221221
x, _ = (np.arange(nx) + 0.5, np.zeros(nx) + 0.5) * transform
222222
_, y = (np.zeros(ny) + 0.5, np.arange(ny) + 0.5) * transform
@@ -239,41 +239,42 @@ def open_rasterio(filename, parse_coordinates=None, chunks=None, cache=None,
239239
# For serialization store as tuple of 6 floats, the last row being
240240
# always (0, 0, 1) per definition (see https://github.com/sgillies/affine)
241241
attrs['transform'] = tuple(transform)[:6]
242-
if hasattr(riods, 'crs') and riods.crs:
242+
if hasattr(riods.value, 'crs') and riods.value.crs:
243243
# CRS is a dict-like object specific to rasterio
244244
# If CRS is not None, we convert it back to a PROJ4 string using
245245
# rasterio itself
246-
attrs['crs'] = riods.crs.to_string()
247-
if hasattr(riods, 'res'):
246+
attrs['crs'] = riods.value.crs.to_string()
247+
if hasattr(riods.value, 'res'):
248248
# (width, height) tuple of pixels in units of CRS
249-
attrs['res'] = riods.res
250-
if hasattr(riods, 'is_tiled'):
249+
attrs['res'] = riods.value.res
250+
if hasattr(riods.value, 'is_tiled'):
251251
# Is the TIF tiled? (bool)
252252
# We cast it to an int for netCDF compatibility
253-
attrs['is_tiled'] = np.uint8(riods.is_tiled)
253+
attrs['is_tiled'] = np.uint8(riods.value.is_tiled)
254254
with warnings.catch_warnings():
255-
# casting riods.transform to a tuple makes this future proof
255+
# casting riods.value.transform to a tuple makes this future proof
256256
warnings.simplefilter('ignore', FutureWarning)
257-
if hasattr(riods, 'transform'):
257+
if hasattr(riods.value, 'transform'):
258258
# Affine transformation matrix (tuple of floats)
259259
# Describes coefficients mapping pixel coordinates to CRS
260-
attrs['transform'] = tuple(riods.transform)
261-
if hasattr(riods, 'nodatavals'):
260+
attrs['transform'] = tuple(riods.value.transform)
261+
if hasattr(riods.value, 'nodatavals'):
262262
# The nodata values for the raster bands
263263
attrs['nodatavals'] = tuple([np.nan if nodataval is None else nodataval
264-
for nodataval in riods.nodatavals])
264+
for nodataval in riods.value.nodatavals])
265265

266266
# Parse extra metadata from tags, if supported
267267
parsers = {'ENVI': _parse_envi}
268268

269-
driver = riods.driver
269+
driver = riods.value.driver
270270
if driver in parsers:
271-
meta = parsers[driver](riods.tags(ns=driver))
271+
meta = parsers[driver](riods.value.tags(ns=driver))
272272

273273
for k, v in meta.items():
274274
# Add values as coordinates if they match the band count,
275275
# as attributes otherwise
276-
if isinstance(v, (list, np.ndarray)) and len(v) == riods.count:
276+
if (isinstance(v, (list, np.ndarray)) and
277+
len(v) == riods.value.count):
277278
coords[k] = ('band', np.asarray(v))
278279
else:
279280
attrs[k] = v

0 commit comments

Comments
 (0)