Skip to content

Commit ff462cc

Browse files
Enforce ruff/tryceratops rules (TRY) (#2054)
* Apply ruff/tryceratops rule TRY004 TRY004 Prefer `TypeError` exception for invalid type * Apply ruff/tryceratops rule TRY201 TRY201 Use `raise` without specifying exception name * Apply ruff/tryceratops rule TRY300 TRY300 Consider moving this statement to an `else` block * Enforce ruff/tryceratops rules (TRY) --------- Co-authored-by: David Stansby <[email protected]>
1 parent d9a142a commit ff462cc

File tree

10 files changed

+20
-14
lines changed

10 files changed

+20
-14
lines changed

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,9 +182,11 @@ extend-select = [
182182
"UP", # pyupgrade
183183
"RSE",
184184
"RUF",
185+
"TRY", # tryceratops
185186
]
186187
ignore = [
187188
"RUF005",
189+
"TRY003",
188190
]
189191

190192
[tool.mypy]

src/zarr/api/asynchronous.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def _like_args(a: ArrayLike, kwargs: dict[str, Any]) -> dict[str, Any]:
6666
if isinstance(a.metadata, ArrayV3Metadata):
6767
new["codecs"] = a.metadata.codecs
6868
else:
69-
raise ValueError(f"Unsupported zarr format: {a.metadata.zarr_format}")
69+
raise TypeError(f"Unsupported zarr format: {a.metadata.zarr_format}")
7070
else:
7171
# TODO: set default values compressor/codecs
7272
# to do this, we may need to evaluate if this is a v2 or v3 array
@@ -862,7 +862,7 @@ async def open_array(
862862

863863
try:
864864
return await AsyncArray.open(store_path, zarr_format=zarr_format)
865-
except FileNotFoundError as e:
865+
except FileNotFoundError:
866866
if store_path.store.mode.create:
867867
return await create(
868868
store=store_path,
@@ -871,7 +871,7 @@ async def open_array(
871871
overwrite=store_path.store.mode.overwrite,
872872
**kwargs,
873873
)
874-
raise e
874+
raise
875875

876876

877877
async def open_like(a: ArrayLike, path: str, **kwargs: Any) -> AsyncArray:

src/zarr/array.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def create_codec_pipeline(metadata: ArrayV2Metadata | ArrayV3Metadata) -> CodecP
8787
[V2Filters(metadata.filters or []), V2Compressor(metadata.compressor)]
8888
)
8989
else:
90-
raise AssertionError
90+
raise TypeError
9191

9292

9393
@dataclass(frozen=True)
@@ -394,7 +394,7 @@ def chunks(self) -> ChunkCoords:
394394
if isinstance(self.metadata.chunk_grid, RegularChunkGrid):
395395
return self.metadata.chunk_grid.chunk_shape
396396
else:
397-
raise ValueError(
397+
raise TypeError(
398398
f"chunk attribute is only available for RegularChunkGrid, this array has a {self.metadata.chunk_grid}"
399399
)
400400

src/zarr/codecs/pipeline.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,7 @@ def codecs_from_list(
492492
"must be preceded by another ArrayArrayCodec. "
493493
f"Got {type(prev_codec)} instead."
494494
)
495-
raise ValueError(msg)
495+
raise TypeError(msg)
496496
array_array += (cur_codec,)
497497

498498
elif isinstance(cur_codec, ArrayBytesCodec):
@@ -501,7 +501,7 @@ def codecs_from_list(
501501
f"Invalid codec order. ArrayBytes codec {cur_codec}"
502502
f" must be preceded by an ArrayArrayCodec. Got {type(prev_codec)} instead."
503503
)
504-
raise ValueError(msg)
504+
raise TypeError(msg)
505505

506506
if array_bytes_maybe is not None:
507507
msg = (
@@ -521,7 +521,7 @@ def codecs_from_list(
521521
)
522522
bytes_bytes += (cur_codec,)
523523
else:
524-
raise AssertionError
524+
raise TypeError
525525

526526
if array_bytes_maybe is None:
527527
raise ValueError("Required ArrayBytesCodec was not found.")

src/zarr/codecs/sharding.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ def validate(self, *, shape: ChunkCoords, dtype: np.dtype[Any], chunk_grid: Chun
387387
"The shard's `chunk_shape` and array's `shape` need to have the same number of dimensions."
388388
)
389389
if not isinstance(chunk_grid, RegularChunkGrid):
390-
raise ValueError("Sharding is only compatible with regular chunk grids.")
390+
raise TypeError("Sharding is only compatible with regular chunk grids.")
391391
if not all(
392392
s % c == 0
393393
for s, c in zip(

src/zarr/group.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -467,9 +467,10 @@ async def contains(self, member: str) -> bool:
467467
# TODO: this can be made more efficient.
468468
try:
469469
await self.getitem(member)
470-
return True
471470
except KeyError:
472471
return False
472+
else:
473+
return True
473474

474475
# todo: decide if this method should be separate from `groups`
475476
async def group_keys(self) -> AsyncGenerator[str, None]:

src/zarr/store/core.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,9 +251,10 @@ async def contains_group(store_path: StorePath, zarr_format: ZarrFormat) -> bool
251251
extant_meta_json = json.loads(extant_meta_bytes.to_bytes())
252252
# we avoid constructing a full metadata document here in the name of speed.
253253
result: bool = extant_meta_json["node_type"] == "group"
254-
return result
255254
except (ValueError, KeyError):
256255
return False
256+
else:
257+
return result
257258
elif zarr_format == 2:
258259
return await (store_path / ZGROUP_JSON).exists()
259260
msg = f"Invalid zarr_format provided. Got {zarr_format}, expected 2 or 3" # type: ignore[unreachable]

src/zarr/store/local.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,10 @@ async def clear(self) -> None:
8787
async def empty(self) -> bool:
8888
try:
8989
subpaths = os.listdir(self.root)
90-
return not subpaths
9190
except FileNotFoundError:
9291
return True
92+
else:
93+
return not subpaths
9394

9495
def __str__(self) -> str:
9596
return f"file://{self.root}"

src/zarr/store/remote.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,6 @@ async def get(
118118
else self._fs._cat_file(path)
119119
)
120120
)
121-
return value
122121

123122
except self.allowed_exceptions:
124123
return None
@@ -127,6 +126,8 @@ async def get(
127126
# this is an s3-specific condition we probably don't want to leak
128127
return prototype.buffer.from_bytes(b"")
129128
raise
129+
else:
130+
return value
130131

131132
async def set(
132133
self,

tests/v3/test_codecs/test_codecs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ def test_invalid_metadata(store: Store) -> None:
382382
fill_value=0,
383383
)
384384
spath2 = StorePath(store, "invalid_endian")
385-
with pytest.raises(ValueError):
385+
with pytest.raises(TypeError):
386386
Array.create(
387387
spath2,
388388
shape=(16, 16),

0 commit comments

Comments
 (0)