Skip to content

Commit 05768ea

Browse files
Apply ruff/flake8-pyi rule PYI055
PYI055 Multiple `type` members in a union. Combine them into one.
1 parent 8b48c1b commit 05768ea

19 files changed

+52
-52
lines changed

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,13 +211,15 @@ extend-select = [
211211
"I", # isort
212212
"ISC", # flake8-implicit-str-concat
213213
"PGH", # pygrep-hooks
214+
"PYI", # flake8-pyi
214215
"RSE", # flake8-raise
215216
"RUF",
216217
"TCH", # flake8-type-checking
217218
"TRY", # tryceratops
218219
"UP", # pyupgrade
219220
]
220221
ignore = [
222+
"PYI013",
221223
"RUF005",
222224
"TRY003",
223225
# https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules

src/zarr/abc/store.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class Store(ABC):
3535
_mode: AccessMode
3636
_is_open: bool
3737

38-
def __init__(self, mode: AccessModeLiteral = "r", *args: Any, **kwargs: Any):
38+
def __init__(self, mode: AccessModeLiteral = "r", *args: Any, **kwargs: Any) -> None:
3939
self._is_open = False
4040
self._mode = AccessMode.from_literal(mode)
4141

src/zarr/codecs/transpose.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,16 +96,14 @@ async def _decode_single(
9696
chunk_spec: ArraySpec,
9797
) -> NDBuffer:
9898
inverse_order = np.argsort(self.order)
99-
chunk_array = chunk_array.transpose(inverse_order)
100-
return chunk_array
99+
return chunk_array.transpose(inverse_order)
101100

102101
async def _encode_single(
103102
self,
104103
chunk_array: NDBuffer,
105104
_chunk_spec: ArraySpec,
106105
) -> NDBuffer | None:
107-
chunk_array = chunk_array.transpose(self.order)
108-
return chunk_array
106+
return chunk_array.transpose(self.order)
109107

110108
def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int:
111109
return input_byte_length

src/zarr/core/array.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def __init__(
110110
metadata: ArrayMetadata,
111111
store_path: StorePath,
112112
order: Literal["C", "F"] | None = None,
113-
):
113+
) -> None:
114114
metadata_parsed = parse_array_metadata(metadata)
115115
order_parsed = parse_indexing_order(order or config.get("array.order"))
116116

@@ -331,8 +331,7 @@ def from_dict(
331331
data: dict[str, JSON],
332332
) -> AsyncArray:
333333
metadata = parse_array_metadata(data)
334-
async_array = cls(metadata=metadata, store_path=store_path)
335-
return async_array
334+
return cls(metadata=metadata, store_path=store_path)
336335

337336
@classmethod
338337
async def open(

src/zarr/core/attributes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414

1515
class Attributes(MutableMapping[str, JSON]):
16-
def __init__(self, obj: Array | Group):
16+
def __init__(self, obj: Array | Group) -> None:
1717
# key=".zattrs", read_only=False, cache=True, synchronizer=None
1818
self._obj = obj
1919

src/zarr/core/buffer/core.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ class Buffer(ABC):
136136
array-like object that must be 1-dim, contiguous, and byte dtype.
137137
"""
138138

139-
def __init__(self, array_like: ArrayLike):
139+
def __init__(self, array_like: ArrayLike) -> None:
140140
if array_like.ndim != 1:
141141
raise ValueError("array_like: only 1-dim allowed")
142142
if array_like.dtype != np.dtype("b"):
@@ -313,7 +313,7 @@ class NDBuffer:
313313
ndarray-like object that is convertible to a regular Numpy array.
314314
"""
315315

316-
def __init__(self, array: NDArrayLike):
316+
def __init__(self, array: NDArrayLike) -> None:
317317
# assert array.ndim > 0
318318
assert array.dtype != object
319319
self._data = array

src/zarr/core/buffer/cpu.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ class Buffer(core.Buffer):
4545
array-like object that must be 1-dim, contiguous, and byte dtype.
4646
"""
4747

48-
def __init__(self, array_like: ArrayLike):
48+
def __init__(self, array_like: ArrayLike) -> None:
4949
super().__init__(array_like)
5050

5151
@classmethod
@@ -143,7 +143,7 @@ class NDBuffer(core.NDBuffer):
143143
ndarray-like object that is convertible to a regular Numpy array.
144144
"""
145145

146-
def __init__(self, array: NDArrayLike):
146+
def __init__(self, array: NDArrayLike) -> None:
147147
super().__init__(array)
148148

149149
@classmethod

src/zarr/core/buffer/gpu.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ class Buffer(core.Buffer):
4848
array-like object that must be 1-dim, contiguous, and byte dtype.
4949
"""
5050

51-
def __init__(self, array_like: ArrayLike):
51+
def __init__(self, array_like: ArrayLike) -> None:
5252
if cp is None:
5353
raise ImportError(
5454
"Cannot use zarr.buffer.gpu.Buffer without cupy. Please install cupy."
@@ -137,7 +137,7 @@ class NDBuffer(core.NDBuffer):
137137
ndarray-like object that is convertible to a regular Numpy array.
138138
"""
139139

140-
def __init__(self, array: NDArrayLike):
140+
def __init__(self, array: NDArrayLike) -> None:
141141
if cp is None:
142142
raise ImportError(
143143
"Cannot use zarr.buffer.gpu.NDBuffer without cupy. Please install cupy."

src/zarr/core/group.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def parse_zarr_format(data: Any) -> ZarrFormat:
5454
def parse_attributes(data: Any) -> dict[str, Any]:
5555
if data is None:
5656
return {}
57-
elif isinstance(data, dict) and all(isinstance(v, str) for v in data.keys()):
57+
elif isinstance(data, dict) and all(isinstance(k, str) for k in data):
5858
return data
5959
msg = f"Expected dict with string keys. Got {type(data)} instead."
6060
raise TypeError(msg)
@@ -104,7 +104,9 @@ def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]:
104104
),
105105
}
106106

107-
def __init__(self, attributes: dict[str, Any] | None = None, zarr_format: ZarrFormat = 3):
107+
def __init__(
108+
self, attributes: dict[str, Any] | None = None, zarr_format: ZarrFormat = 3
109+
) -> None:
108110
attributes_parsed = parse_attributes(attributes)
109111
zarr_format_parsed = parse_zarr_format(zarr_format)
110112

@@ -202,11 +204,10 @@ def from_dict(
202204
store_path: StorePath,
203205
data: dict[str, Any],
204206
) -> AsyncGroup:
205-
group = cls(
207+
return cls(
206208
metadata=GroupMetadata.from_dict(data),
207209
store_path=store_path,
208210
)
209-
return group
210211

211212
async def getitem(
212213
self,
@@ -888,8 +889,7 @@ def members(self, max_depth: int | None = 0) -> tuple[tuple[str, Array | Group],
888889
"""
889890
_members = self._sync_iter(self._async_group.members(max_depth=max_depth))
890891

891-
result = tuple((kv[0], _parse_async_node(kv[1])) for kv in _members)
892-
return result
892+
return tuple((kv[0], _parse_async_node(kv[1])) for kv in _members)
893893

894894
def __contains__(self, member: str) -> bool:
895895
return self._sync(self._async_group.contains(member))

src/zarr/core/indexing.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ class ArrayIndexError(IndexError):
5555
class BoundsCheckError(IndexError):
5656
_msg = ""
5757

58-
def __init__(self, dim_len: int):
58+
def __init__(self, dim_len: int) -> None:
5959
self._msg = f"index out of bounds for dimension with length {dim_len}"
6060

6161

@@ -247,7 +247,7 @@ class IntDimIndexer:
247247
dim_chunk_len: int
248248
nitems: int = 1
249249

250-
def __init__(self, dim_sel: int, dim_len: int, dim_chunk_len: int):
250+
def __init__(self, dim_sel: int, dim_len: int, dim_chunk_len: int) -> None:
251251
object.__setattr__(self, "dim_sel", normalize_integer_selection(dim_sel, dim_len))
252252
object.__setattr__(self, "dim_len", dim_len)
253253
object.__setattr__(self, "dim_chunk_len", dim_chunk_len)
@@ -271,7 +271,7 @@ class SliceDimIndexer:
271271
stop: int
272272
step: int
273273

274-
def __init__(self, dim_sel: slice, dim_len: int, dim_chunk_len: int):
274+
def __init__(self, dim_sel: slice, dim_len: int, dim_chunk_len: int) -> None:
275275
# normalize
276276
start, stop, step = dim_sel.indices(dim_len)
277277
if step < 1:
@@ -445,7 +445,7 @@ def __init__(
445445
selection: BasicSelection,
446446
shape: ChunkCoords,
447447
chunk_grid: ChunkGrid,
448-
):
448+
) -> None:
449449
chunk_shape = get_chunk_shape(chunk_grid)
450450
# handle ellipsis
451451
selection_normalized = replace_ellipsis(selection, shape)
@@ -501,7 +501,7 @@ class BoolArrayDimIndexer:
501501
nitems: int
502502
dim_chunk_ixs: npt.NDArray[np.intp]
503503

504-
def __init__(self, dim_sel: npt.NDArray[np.bool_], dim_len: int, dim_chunk_len: int):
504+
def __init__(self, dim_sel: npt.NDArray[np.bool_], dim_len: int, dim_chunk_len: int) -> None:
505505
# check number of dimensions
506506
if not is_bool_array(dim_sel, 1):
507507
raise IndexError("Boolean arrays in an orthogonal selection must be 1-dimensional only")
@@ -618,7 +618,7 @@ def __init__(
618618
wraparound: bool = True,
619619
boundscheck: bool = True,
620620
order: Order = Order.UNKNOWN,
621-
):
621+
) -> None:
622622
# ensure 1d array
623623
dim_sel = np.asanyarray(dim_sel)
624624
if not is_integer_array(dim_sel, 1):
@@ -758,7 +758,7 @@ class OrthogonalIndexer(Indexer):
758758
is_advanced: bool
759759
drop_axes: tuple[int, ...]
760760

761-
def __init__(self, selection: Selection, shape: ChunkCoords, chunk_grid: ChunkGrid):
761+
def __init__(self, selection: Selection, shape: ChunkCoords, chunk_grid: ChunkGrid) -> None:
762762
chunk_shape = get_chunk_shape(chunk_grid)
763763

764764
# handle ellipsis
@@ -865,7 +865,9 @@ class BlockIndexer(Indexer):
865865
shape: ChunkCoords
866866
drop_axes: ChunkCoords
867867

868-
def __init__(self, selection: BasicSelection, shape: ChunkCoords, chunk_grid: ChunkGrid):
868+
def __init__(
869+
self, selection: BasicSelection, shape: ChunkCoords, chunk_grid: ChunkGrid
870+
) -> None:
869871
chunk_shape = get_chunk_shape(chunk_grid)
870872

871873
# handle ellipsis
@@ -990,7 +992,9 @@ class CoordinateIndexer(Indexer):
990992
chunk_shape: ChunkCoords
991993
drop_axes: ChunkCoords
992994

993-
def __init__(self, selection: CoordinateSelection, shape: ChunkCoords, chunk_grid: ChunkGrid):
995+
def __init__(
996+
self, selection: CoordinateSelection, shape: ChunkCoords, chunk_grid: ChunkGrid
997+
) -> None:
994998
chunk_shape = get_chunk_shape(chunk_grid)
995999

9961000
cdata_shape: ChunkCoords
@@ -1107,7 +1111,7 @@ def __iter__(self) -> Iterator[ChunkProjection]:
11071111

11081112
@dataclass(frozen=True)
11091113
class MaskIndexer(CoordinateIndexer):
1110-
def __init__(self, selection: MaskSelection, shape: ChunkCoords, chunk_grid: ChunkGrid):
1114+
def __init__(self, selection: MaskSelection, shape: ChunkCoords, chunk_grid: ChunkGrid) -> None:
11111115
# some initial normalization
11121116
selection_normalized = cast(tuple[MaskSelection], ensure_tuple(selection))
11131117
selection_normalized = cast(tuple[MaskSelection], replace_lists(selection_normalized))

src/zarr/registry.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def fully_qualified_name(cls: type) -> str:
107107

108108

109109
def register_codec(key: str, codec_cls: type[Codec]) -> None:
110-
if key not in __codec_registries.keys():
110+
if key not in __codec_registries:
111111
__codec_registries[key] = Registry()
112112
__codec_registries[key].register(codec_cls)
113113

@@ -158,7 +158,7 @@ def get_pipeline_class(reload_config: bool = False) -> type[CodecPipeline]:
158158
if pipeline_class:
159159
return pipeline_class
160160
raise BadConfigError(
161-
f"Pipeline class '{path}' not found in registered pipelines: {list(__pipeline_registry.keys())}."
161+
f"Pipeline class '{path}' not found in registered pipelines: {list(__pipeline_registry)}."
162162
)
163163

164164

@@ -172,7 +172,7 @@ def get_buffer_class(reload_config: bool = False) -> type[Buffer]:
172172
if buffer_class:
173173
return buffer_class
174174
raise BadConfigError(
175-
f"Buffer class '{path}' not found in registered buffers: {list(__buffer_registry.keys())}."
175+
f"Buffer class '{path}' not found in registered buffers: {list(__buffer_registry)}."
176176
)
177177

178178

@@ -185,7 +185,7 @@ def get_ndbuffer_class(reload_config: bool = False) -> type[NDBuffer]:
185185
if ndbuffer_class:
186186
return ndbuffer_class
187187
raise BadConfigError(
188-
f"NDBuffer class '{path}' not found in registered buffers: {list(__ndbuffer_registry.keys())}."
188+
f"NDBuffer class '{path}' not found in registered buffers: {list(__ndbuffer_registry)}."
189189
)
190190

191191

src/zarr/store/common.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,14 @@ def _dereference_path(root: str, path: str) -> str:
2323
assert isinstance(path, str)
2424
root = root.rstrip("/")
2525
path = f"{root}/{path}" if root else path
26-
path = path.rstrip("/")
27-
return path
26+
return path.rstrip("/")
2827

2928

3029
class StorePath:
3130
store: Store
3231
path: str
3332

34-
def __init__(self, store: Store, path: str | None = None):
33+
def __init__(self, store: Store, path: str | None = None) -> None:
3534
self.store = store
3635
self.path = path or ""
3736

@@ -265,8 +264,7 @@ async def contains_array(store_path: StorePath, zarr_format: ZarrFormat) -> bool
265264
except (ValueError, KeyError):
266265
return False
267266
elif zarr_format == 2:
268-
result = await (store_path / ZARRAY_JSON).exists()
269-
return result
267+
return await (store_path / ZARRAY_JSON).exists()
270268
msg = f"Invalid zarr_format provided. Got {zarr_format}, expected 2 or 3"
271269
raise ValueError(msg)
272270

src/zarr/store/local.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ class LocalStore(Store):
7979

8080
root: Path
8181

82-
def __init__(self, root: Path | str, *, mode: AccessModeLiteral = "r"):
82+
def __init__(self, root: Path | str, *, mode: AccessModeLiteral = "r") -> None:
8383
super().__init__(mode=mode)
8484
if isinstance(root, str):
8585
root = Path(root)

src/zarr/store/memory.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def __init__(
3030
store_dict: MutableMapping[str, Buffer] | None = None,
3131
*,
3232
mode: AccessModeLiteral = "r",
33-
):
33+
) -> None:
3434
super().__init__(mode=mode)
3535
if store_dict is None:
3636
store_dict = {}
@@ -80,8 +80,7 @@ async def get_partial_values(
8080
async def _get(key: str, byte_range: tuple[int, int | None]) -> Buffer | None:
8181
return await self.get(key, prototype=prototype, byte_range=byte_range)
8282

83-
vals = await concurrent_map(key_ranges, _get, limit=None)
84-
return vals
83+
return await concurrent_map(key_ranges, _get, limit=None)
8584

8685
async def exists(self, key: str) -> bool:
8786
return key in self._store_dict
@@ -137,7 +136,7 @@ async def list_dir(self, prefix: str) -> AsyncGenerator[str, None]:
137136
prefix = prefix[:-1]
138137

139138
if prefix == "":
140-
keys_unique = set(k.split("/")[0] for k in self._store_dict.keys())
139+
keys_unique = set(k.split("/")[0] for k in self._store_dict)
141140
else:
142141
# Our dictionary doesn't contain directory markers, but we want to include
143142
# a pseudo directory when there's a nested item and we're listing an
@@ -166,7 +165,7 @@ def __init__(
166165
store_dict: MutableMapping[str, Buffer] | None = None,
167166
*,
168167
mode: AccessModeLiteral = "r",
169-
):
168+
) -> None:
170169
super().__init__(mode=mode)
171170
if store_dict:
172171
self._store_dict = {k: gpu.Buffer.from_buffer(store_dict[k]) for k in iter(store_dict)}

src/zarr/store/remote.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def __init__(
3939
mode: AccessModeLiteral = "r",
4040
path: str = "/",
4141
allowed_exceptions: tuple[type[Exception], ...] = ALLOWED_EXCEPTIONS,
42-
):
42+
) -> None:
4343
"""
4444
Parameters
4545
----------
@@ -49,6 +49,7 @@ def __init__(
4949
keys, rather than some other IO failure
5050
storage_options: passed on to fsspec to make the filesystem instance. If url is a UPath,
5151
this must not be used.
52+
5253
"""
5354
super().__init__(mode=mode)
5455
self.fs = fs

src/zarr/testing/strategies.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,5 +171,4 @@ def key_ranges(keys: SearchStrategy = node_names) -> SearchStrategy[list]:
171171
st.none() | st.integers(min_value=0), st.none() | st.integers(min_value=0)
172172
)
173173
key_tuple = st.tuples(keys, byte_ranges)
174-
key_range_st = st.lists(key_tuple, min_size=1, max_size=10)
175-
return key_range_st
174+
return st.lists(key_tuple, min_size=1, max_size=10)

0 commit comments

Comments
 (0)