Skip to content

Commit 127a78a

Browse files
Improve exception trace with RUF B904 (#1641)
Co-authored-by: Martin Durant <[email protected]>
1 parent 09b07d0 commit 127a78a

File tree

10 files changed

+51
-43
lines changed

10 files changed

+51
-43
lines changed

fsspec/core.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -639,7 +639,7 @@ def get_fs_token_paths(
639639
if isinstance(urlpath, (list, tuple, set)):
640640
if not urlpath:
641641
raise ValueError("empty urlpath sequence")
642-
urlpath0 = stringify_path(list(urlpath)[0])
642+
urlpath0 = stringify_path(next(iter(urlpath)))
643643
else:
644644
urlpath0 = stringify_path(urlpath)
645645
storage_options = storage_options or {}

fsspec/fuse.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ def getattr(self, path, fh=None):
3131
path = "".join([self.root, path.lstrip("/")]).rstrip("/")
3232
try:
3333
info = self.fs.info(path)
34-
except FileNotFoundError:
35-
raise FuseOSError(ENOENT)
34+
except FileNotFoundError as exc:
35+
raise FuseOSError(ENOENT) from exc
3636

3737
data = {"st_uid": info.get("uid", 1000), "st_gid": info.get("gid", 1000)}
3838
perm = info.get("mode", 0o777)
@@ -119,8 +119,8 @@ def unlink(self, path):
119119
fn = "".join([self.root, path.lstrip("/")])
120120
try:
121121
self.fs.rm(fn, False)
122-
except (OSError, FileNotFoundError):
123-
raise FuseOSError(EIO)
122+
except (OSError, FileNotFoundError) as exc:
123+
raise FuseOSError(EIO) from exc
124124

125125
def release(self, path, fh):
126126
try:

fsspec/gui.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,10 @@ def _repr_mimebundle_(self, *args, **kwargs):
9393
"""Display in a notebook or a server"""
9494
try:
9595
return self.panel._repr_mimebundle_(*args, **kwargs)
96-
except (ValueError, AttributeError):
97-
raise NotImplementedError("Panel does not seem to be set up properly")
96+
except (ValueError, AttributeError) as exc:
97+
raise NotImplementedError(
98+
"Panel does not seem to be set up properly"
99+
) from exc
98100

99101
def connect(self, signal, slot):
100102
"""Associate call back with given event

fsspec/implementations/dbfs.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def ls(self, path, detail=True, **kwargs):
7777
)
7878
except DatabricksException as e:
7979
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
80-
raise FileNotFoundError(e.message)
80+
raise FileNotFoundError(e.message) from e
8181

8282
raise e
8383
files = r["files"]
@@ -123,7 +123,7 @@ def makedirs(self, path, exist_ok=True):
123123
self._send_to_api(method="post", endpoint="mkdirs", json={"path": path})
124124
except DatabricksException as e:
125125
if e.error_code == "RESOURCE_ALREADY_EXISTS":
126-
raise FileExistsError(e.message)
126+
raise FileExistsError(e.message) from e
127127

128128
raise e
129129
self.invalidate_cache(self._parent(path))
@@ -169,7 +169,7 @@ def rm(self, path, recursive=False, **kwargs):
169169
self.rm(path=path, recursive=recursive)
170170
elif e.error_code == "IO_ERROR":
171171
# Using the same exception as the os module would use here
172-
raise OSError(e.message)
172+
raise OSError(e.message) from e
173173

174174
raise e
175175
self.invalidate_cache(self._parent(path))
@@ -212,9 +212,9 @@ def mv(
212212
)
213213
except DatabricksException as e:
214214
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
215-
raise FileNotFoundError(e.message)
215+
raise FileNotFoundError(e.message) from e
216216
elif e.error_code == "RESOURCE_ALREADY_EXISTS":
217-
raise FileExistsError(e.message)
217+
raise FileExistsError(e.message) from e
218218

219219
raise e
220220
self.invalidate_cache(self._parent(source_path))
@@ -264,9 +264,9 @@ def _send_to_api(self, method, endpoint, json):
264264
try:
265265
exception_json = e.response.json()
266266
except Exception:
267-
raise e
267+
raise e from None
268268

269-
raise DatabricksException(**exception_json)
269+
raise DatabricksException(**exception_json) from e
270270

271271
return r.json()
272272

@@ -297,7 +297,7 @@ def _create_handle(self, path, overwrite=True):
297297
return r["handle"]
298298
except DatabricksException as e:
299299
if e.error_code == "RESOURCE_ALREADY_EXISTS":
300-
raise FileExistsError(e.message)
300+
raise FileExistsError(e.message) from e
301301

302302
raise e
303303

@@ -314,7 +314,7 @@ def _close_handle(self, handle):
314314
self._send_to_api(method="post", endpoint="close", json={"handle": handle})
315315
except DatabricksException as e:
316316
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
317-
raise FileNotFoundError(e.message)
317+
raise FileNotFoundError(e.message) from e
318318

319319
raise e
320320

@@ -342,9 +342,9 @@ def _add_data(self, handle, data):
342342
)
343343
except DatabricksException as e:
344344
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
345-
raise FileNotFoundError(e.message)
345+
raise FileNotFoundError(e.message) from e
346346
elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED":
347-
raise ValueError(e.message)
347+
raise ValueError(e.message) from e
348348

349349
raise e
350350

@@ -372,9 +372,9 @@ def _get_data(self, path, start, end):
372372
return base64.b64decode(r["data"])
373373
except DatabricksException as e:
374374
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
375-
raise FileNotFoundError(e.message)
375+
raise FileNotFoundError(e.message) from e
376376
elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]:
377-
raise ValueError(e.message)
377+
raise ValueError(e.message) from e
378378

379379
raise e
380380

fsspec/implementations/ftp.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,8 @@ def ls(self, path, detail=True, **kwargs):
122122
info = self.info(path)
123123
if info["type"] == "file":
124124
out = [(path, info)]
125-
except (Error, IndexError):
126-
raise FileNotFoundError(path)
125+
except (Error, IndexError) as exc:
126+
raise FileNotFoundError(path) from exc
127127
files = self.dircache.get(path, out)
128128
if not detail:
129129
return sorted([fn for fn, details in files])
@@ -137,9 +137,9 @@ def info(self, path, **kwargs):
137137
return {"name": "/", "size": 0, "type": "directory"}
138138
files = self.ls(self._parent(path).lstrip("/"), True)
139139
try:
140-
out = [f for f in files if f["name"] == path][0]
141-
except IndexError:
142-
raise FileNotFoundError(path)
140+
out = next(f for f in files if f["name"] == path)
141+
except StopIteration as exc:
142+
raise FileNotFoundError(path) from exc
143143
return out
144144

145145
def get_file(self, rpath, lpath, **kwargs):

fsspec/implementations/memory.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -224,8 +224,8 @@ def cat_file(self, path, start=None, end=None, **kwargs):
224224
path = self._strip_protocol(path)
225225
try:
226226
return bytes(self.store[path].getbuffer()[start:end])
227-
except KeyError:
228-
raise FileNotFoundError(path)
227+
except KeyError as e:
228+
raise FileNotFoundError(path) from e
229229

230230
def _rm(self, path):
231231
path = self._strip_protocol(path)
@@ -238,15 +238,15 @@ def modified(self, path):
238238
path = self._strip_protocol(path)
239239
try:
240240
return self.store[path].modified
241-
except KeyError:
242-
raise FileNotFoundError(path)
241+
except KeyError as e:
242+
raise FileNotFoundError(path) from e
243243

244244
def created(self, path):
245245
path = self._strip_protocol(path)
246246
try:
247247
return self.store[path].created
248-
except KeyError:
249-
raise FileNotFoundError(path)
248+
except KeyError as e:
249+
raise FileNotFoundError(path) from e
250250

251251
def rm(self, path, recursive=False, maxdepth=None):
252252
if isinstance(path, str):

fsspec/implementations/reference.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def __str__(self):
3535

3636

3737
def _first(d):
38-
return list(d.values())[0]
38+
return next(iter(d.values()))
3939

4040

4141
def _prot_in_references(path, references):
@@ -291,8 +291,8 @@ def _load_one_key(self, key):
291291
# Chunk keys can be loaded from row group and cached in LRU cache
292292
try:
293293
refs = self.open_refs(field, record)
294-
except (ValueError, TypeError, FileNotFoundError):
295-
raise KeyError(key)
294+
except (ValueError, TypeError, FileNotFoundError) as exc:
295+
raise KeyError(key) from exc
296296
columns = ["path", "offset", "size", "raw"]
297297
selection = [refs[c][ri] if c in refs else None for c in columns]
298298
raw = selection[-1]
@@ -732,8 +732,8 @@ def _cat_common(self, path, start=None, end=None):
732732
logger.debug(f"cat: {path}")
733733
try:
734734
part = self.references[path]
735-
except KeyError:
736-
raise FileNotFoundError(path)
735+
except KeyError as exc:
736+
raise FileNotFoundError(path) from exc
737737
if isinstance(part, str):
738738
part = part.encode()
739739
if isinstance(part, bytes):

fsspec/implementations/tests/test_cached.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -685,7 +685,9 @@ def test_local_filecache_basic(local_filecache):
685685
assert "cache" in os.listdir(cache_location)
686686

687687
# the file in the location contains the right data
688-
fn = list(fs._metadata.cached_files[-1].values())[0]["fn"] # this is a hash value
688+
fn = next(iter(fs._metadata.cached_files[-1].values()))[
689+
"fn"
690+
] # this is a hash value
689691
assert fn in os.listdir(cache_location)
690692
with open(os.path.join(cache_location, fn), "rb") as f:
691693
assert f.read() == data
@@ -730,7 +732,9 @@ def test_local_filecache_gets_from_original_if_cache_deleted(local_filecache):
730732
assert f.read() == new_data
731733

732734
# the file in the location contains the right data
733-
fn = list(fs._metadata.cached_files[-1].values())[0]["fn"] # this is a hash value
735+
fn = next(iter(fs._metadata.cached_files[-1].values()))[
736+
"fn"
737+
] # this is a hash value
734738
assert fn in os.listdir(cache_location)
735739
with open(os.path.join(cache_location, fn), "rb") as f:
736740
assert f.read() == new_data
@@ -753,7 +757,7 @@ def test_local_filecache_with_new_cache_location_makes_a_new_copy(local_filecach
753757
assert f.read() == data
754758

755759
# the file in the location contains the right data
756-
fn = list(new_fs._metadata.cached_files[-1].values())[0][
760+
fn = next(iter(new_fs._metadata.cached_files[-1].values()))[
757761
"fn"
758762
] # this is a hash value
759763
assert fn in os.listdir(old_cache_location)

fsspec/mapping.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,10 +153,10 @@ def __getitem__(self, key, default=None):
153153
k = self._key_to_str(key)
154154
try:
155155
result = self.fs.cat(k)
156-
except self.missing_exceptions:
156+
except self.missing_exceptions as exc:
157157
if default is not None:
158158
return default
159-
raise KeyError(key)
159+
raise KeyError(key) from exc
160160
return result
161161

162162
def pop(self, key, default=None):
@@ -184,8 +184,8 @@ def __delitem__(self, key):
184184
"""Remove key"""
185185
try:
186186
self.fs.rm(self._key_to_str(key))
187-
except: # noqa: E722
188-
raise KeyError
187+
except Exception as exc:
188+
raise KeyError from exc
189189

190190
def __contains__(self, key):
191191
"""Does key exist in mapping?"""

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ select = [
154154
# fix noqas in fsspec/implementations/http.py
155155
"ASYNC",
156156
"B",
157+
"B904",
157158
"C4",
158159
"G",
159160
"E4",
@@ -177,6 +178,7 @@ select = [
177178
# "PT", enable in later PR
178179
"PYI",
179180
"RUF006",
181+
"RUF015",
180182
"RUF024",
181183
"SLOT",
182184
"SIM101",

0 commit comments

Comments
 (0)