Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enforce ruff/tryceratops rules (TRY) #2054

Merged
merged 5 commits into from
Aug 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,11 @@ extend-select = [
"UP", # pyupgrade
"RSE",
"RUF",
"TRY", # tryceratops
]
ignore = [
"RUF005",
"TRY003",
]

[tool.mypy]
Expand Down
6 changes: 3 additions & 3 deletions src/zarr/api/asynchronous.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def _like_args(a: ArrayLike, kwargs: dict[str, Any]) -> dict[str, Any]:
if isinstance(a.metadata, ArrayV3Metadata):
new["codecs"] = a.metadata.codecs
else:
raise ValueError(f"Unsupported zarr format: {a.metadata.zarr_format}")
raise TypeError(f"Unsupported zarr format: {a.metadata.zarr_format}")
else:
# TODO: set default values compressor/codecs
# to do this, we may need to evaluate if this is a v2 or v3 array
Expand Down Expand Up @@ -862,7 +862,7 @@ async def open_array(

try:
return await AsyncArray.open(store_path, zarr_format=zarr_format)
except FileNotFoundError as e:
except FileNotFoundError:
if store_path.store.mode.create:
return await create(
store=store_path,
Expand All @@ -871,7 +871,7 @@ async def open_array(
overwrite=store_path.store.mode.overwrite,
**kwargs,
)
raise e
raise


async def open_like(a: ArrayLike, path: str, **kwargs: Any) -> AsyncArray:
Expand Down
4 changes: 2 additions & 2 deletions src/zarr/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def create_codec_pipeline(metadata: ArrayV2Metadata | ArrayV3Metadata) -> CodecP
[V2Filters(metadata.filters or []), V2Compressor(metadata.compressor)]
)
else:
raise AssertionError
raise TypeError


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

Expand Down
6 changes: 3 additions & 3 deletions src/zarr/codecs/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ def codecs_from_list(
"must be preceded by another ArrayArrayCodec. "
f"Got {type(prev_codec)} instead."
)
raise ValueError(msg)
raise TypeError(msg)
array_array += (cur_codec,)

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

if array_bytes_maybe is not None:
msg = (
Expand All @@ -521,7 +521,7 @@ def codecs_from_list(
)
bytes_bytes += (cur_codec,)
else:
raise AssertionError
raise TypeError

if array_bytes_maybe is None:
raise ValueError("Required ArrayBytesCodec was not found.")
Expand Down
2 changes: 1 addition & 1 deletion src/zarr/codecs/sharding.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ def validate(self, *, shape: ChunkCoords, dtype: np.dtype[Any], chunk_grid: Chun
"The shard's `chunk_shape` and array's `shape` need to have the same number of dimensions."
)
if not isinstance(chunk_grid, RegularChunkGrid):
raise ValueError("Sharding is only compatible with regular chunk grids.")
raise TypeError("Sharding is only compatible with regular chunk grids.")
if not all(
s % c == 0
for s, c in zip(
Expand Down
3 changes: 2 additions & 1 deletion src/zarr/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,9 +467,10 @@ async def contains(self, member: str) -> bool:
# TODO: this can be made more efficient.
try:
await self.getitem(member)
return True
except KeyError:
return False
else:
return True

# todo: decide if this method should be separate from `groups`
async def group_keys(self) -> AsyncGenerator[str, None]:
Expand Down
3 changes: 2 additions & 1 deletion src/zarr/store/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,9 +251,10 @@ async def contains_group(store_path: StorePath, zarr_format: ZarrFormat) -> bool
extant_meta_json = json.loads(extant_meta_bytes.to_bytes())
# we avoid constructing a full metadata document here in the name of speed.
result: bool = extant_meta_json["node_type"] == "group"
return result
except (ValueError, KeyError):
return False
else:
return result
elif zarr_format == 2:
return await (store_path / ZGROUP_JSON).exists()
msg = f"Invalid zarr_format provided. Got {zarr_format}, expected 2 or 3" # type: ignore[unreachable]
Expand Down
3 changes: 2 additions & 1 deletion src/zarr/store/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,10 @@ async def clear(self) -> None:
async def empty(self) -> bool:
try:
subpaths = os.listdir(self.root)
return not subpaths
except FileNotFoundError:
return True
else:
return not subpaths

def __str__(self) -> str:
return f"file://{self.root}"
Expand Down
3 changes: 2 additions & 1 deletion src/zarr/store/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ async def get(
else self._fs._cat_file(path)
)
)
return value

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

async def set(
self,
Expand Down
2 changes: 1 addition & 1 deletion tests/v3/test_codecs/test_codecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ def test_invalid_metadata(store: Store) -> None:
fill_value=0,
)
spath2 = StorePath(store, "invalid_endian")
with pytest.raises(ValueError):
with pytest.raises(TypeError):
Array.create(
spath2,
shape=(16, 16),
Expand Down