Skip to content

Commit d3d64e3

Browse files
jorisvandenbosschedarribas
authored andcommitted
Fix unclosed file ResourceWarning (#107)
1 parent 3e48cf9 commit d3d64e3

File tree

2 files changed

+17
-17
lines changed

2 files changed

+17
-17
lines changed

contextily/plotting.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -126,16 +126,16 @@ def add_basemap(
126126
import rasterio as rio
127127

128128
# Read file
129-
raster = rio.open(url)
130-
image = np.array([band for band in raster.read()])
131-
# Warp
132-
if (crs is not None) and (raster.crs != crs):
133-
image, raster = _warper(
134-
image, raster.transform, raster.crs, crs, resampling
135-
)
136-
image = image.transpose(1, 2, 0)
137-
bb = raster.bounds
138-
extent = bb.left, bb.right, bb.bottom, bb.top
129+
with rio.open(url) as raster:
130+
image = np.array([band for band in raster.read()])
131+
# Warp
132+
if (crs is not None) and (raster.crs != crs):
133+
image, raster = _warper(
134+
image, raster.transform, raster.crs, crs, resampling
135+
)
136+
image = image.transpose(1, 2, 0)
137+
bb = raster.bounds
138+
extent = bb.left, bb.right, bb.bottom, bb.top
139139
# Plotting
140140
img = ax.imshow(
141141
image, extent=extent, interpolation=interpolation, **extra_imshow_args

contextily/tile.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def bounds2raster(
105105
resY = (y[-1] - y[0]) / h
106106
transform = from_origin(x[0] - resX / 2, y[-1] + resY / 2, resX, resY)
107107
# ---
108-
raster = rio.open(
108+
with rio.open(
109109
path,
110110
"w",
111111
driver="GTiff",
@@ -115,10 +115,9 @@ def bounds2raster(
115115
dtype=str(Z.dtype.name),
116116
crs="epsg:3857",
117117
transform=transform,
118-
)
119-
for band in range(b):
120-
raster.write(Z[:, :, band], band + 1)
121-
raster.close()
118+
) as raster:
119+
for band in range(b):
120+
raster.write(Z[:, :, band], band + 1)
122121
return Z, ext
123122

124123

@@ -229,8 +228,9 @@ def _fetch_tile(tile_url, wait, max_retries):
229228
request = _retryer(tile_url, wait, max_retries)
230229
with io.BytesIO(request.content) as image_stream:
231230
image = Image.open(image_stream).convert("RGB")
232-
image = np.asarray(image)
233-
return image
231+
array = np.asarray(image)
232+
image.close()
233+
return array
234234

235235

236236
def warp_tiles(img, extent, t_crs="EPSG:4326", resampling=Resampling.bilinear):

0 commit comments

Comments
 (0)