Skip to content

Commit 79f87f6

Browse files
Apply Sourcery suggestions
1 parent ce3cb38 commit 79f87f6

8 files changed

Lines changed: 26 additions & 37 deletions

File tree

src/blosc2/core.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1092,9 +1092,7 @@ def detect_number_of_cores() -> int:
10921092
# Dictionaries for the maps between compressor names and libs
10931093
codecs = compressor_list(plugins=True)
10941094
# Map for compression libraries and versions
1095-
clib_versions = {}
1096-
for codec in compressor_list(plugins=False):
1097-
clib_versions[codec.name] = clib_info(codec)[1].decode("utf-8")
1095+
clib_versions = {codec.name: clib_info(codec)[1].decode("utf-8") for codec in compressor_list(plugins=False)}
10981096

10991097

11001098
def os_release_pretty_name():
@@ -1422,15 +1420,14 @@ def compute_partition(nitems, maxshape, minpart=None):
14221420
if rsize <= max_items:
14231421
# rsize = rsize if size % rsize == 0 else nearest_divisor(size, rsize)
14241422
rsize = rsize if size % rsize == 0 else blosc2_ext.nearest_divisor(size, rsize)
1425-
partition[-(i + 1)] = rsize
14261423
else:
14271424
rsize = max(max_items, minsize)
14281425
# new_rsize = rsize if size % rsize == 0 else nearest_divisor(size, rsize, strict=True)
14291426
new_rsize = rsize if size % rsize == 0 else blosc2_ext.nearest_divisor(size, rsize, strict=True)
14301427
# If the new rsize is not too far from the original rsize, use it
14311428
if rsize // 2 < new_rsize < rsize * 2:
14321429
rsize = new_rsize
1433-
partition[-(i + 1)] = rsize
1430+
partition[-(i + 1)] = rsize
14341431
max_items //= rsize
14351432

14361433
return partition

src/blosc2/helpers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def wrapper(child_func):
3232
# Next parameter starts, stop copying lines
3333
break
3434
matching_lines.append(line)
35-
assert len(matching_lines) > 0, (
35+
assert matching_lines, (
3636
f"Could not extract the parameter {parameter} from the docstring of {parent_func.__name__}"
3737
)
3838

src/blosc2/lazyexpr.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -657,7 +657,7 @@ def conserve_functions( # noqa: C901
657657
expression: str,
658658
operands_old: dict[str, blosc2.NDArray | blosc2.LazyExpr],
659659
operands_new: dict[str, blosc2.NDArray | blosc2.LazyExpr],
660-
) -> tuple(str, dict[str, blosc2.NDArray]):
660+
) -> tuple[str, dict[str, blosc2.NDArray]]:
661661
"""
662662
Given an expression in string form, return its operands.
663663
@@ -738,8 +738,6 @@ def visit_Name(self, node):
738738
node.id = newexpr.replace(";", "")
739739
else:
740740
node.id = self.update_func(localop)
741-
else:
742-
pass
743741
self.generic_visit(node)
744742

745743
def visit_Call(self, node):
@@ -784,7 +782,7 @@ def convert_to_slice(expression):
784782
slicer = str(slicer)
785783
# use slice so that lazyexpr uses blosc arrays internally
786784
# (and doesn't decompress according to getitem syntax)
787-
new_expr += ".slice(" + slicer + ")"
785+
new_expr += f".slice({slicer})"
788786
skip_to_char = i + k + 1
789787
else:
790788
new_expr += expr_i
@@ -833,11 +831,11 @@ def extract_numpy_scalars(expr: str):
833831

834832
def validate_inputs(inputs: dict, out=None, reduce=False) -> tuple: # noqa: C901
835833
"""Validate the inputs for the expression."""
836-
if len(inputs) == 0:
834+
if not inputs:
837835
if out is None:
838836
raise ValueError(
839837
"You really want to pass at least one input or one output for building a LazyArray."
840-
" Maybe you want blosc2.empty() instead?"
838+
" Maybe you want blosc2.empty() instead?"
841839
)
842840
if isinstance(out, blosc2.NDArray):
843841
return out.shape, out.chunks, out.blocks, True
@@ -854,7 +852,7 @@ def validate_inputs(inputs: dict, out=None, reduce=False) -> tuple: # noqa: C90
854852

855853
# More checks specific of NDArray inputs
856854
NDinputs = [input for input in inputs if hasattr(input, "chunks")]
857-
if len(NDinputs) == 0:
855+
if not NDinputs:
858856
# All inputs are NumPy arrays, so we cannot take the fast path
859857
if inputs and hasattr(inputs[0], "shape"):
860858
shape = inputs[0].shape
@@ -895,7 +893,7 @@ def is_full_slice(item):
895893
elif isinstance(item, int | bool):
896894
return False
897895
else:
898-
return item == slice(None, None, None) or item == Ellipsis
896+
return item in (slice(None, None, None), Ellipsis)
899897

900898

901899
def do_slices_intersect(slice1: list | tuple, slice2: list | tuple) -> bool:
@@ -1925,7 +1923,7 @@ def fuse_expressions(expr, new_base, dup_op):
19251923
if i < skip_to_char:
19261924
continue
19271925
if expr_i == "o":
1928-
if i > 0 and (expr[i - 1] != " " and expr[i - 1] != "("):
1926+
if i > 0 and expr[i - 1] not in {" ", "("}:
19291927
# Not a variable
19301928
new_expr += expr_i
19311929
continue
@@ -2960,18 +2958,18 @@ def info(self):
29602958

29612959
@property
29622960
def info_items(self):
2963-
items = []
2964-
items += [("type", f"{self.__class__.__name__}")]
29652961
inputs = {}
29662962
for key, value in self.inputs_dict.items():
29672963
if isinstance(value, np.ndarray | blosc2.NDArray | blosc2.C2Array):
29682964
inputs[key] = f"<{value.__class__.__name__}> {value.shape} {value.dtype}"
29692965
else:
29702966
inputs[key] = str(value)
2971-
items += [("inputs", inputs)]
2972-
items += [("shape", self.shape)]
2973-
items += [("dtype", self.dtype)]
2974-
return items
2967+
return [
2968+
("type", f"{self.__class__.__name__}"),
2969+
("inputs", inputs),
2970+
("shape", self.shape),
2971+
("dtype", self.dtype),
2972+
]
29752973

29762974
# TODO: indices and sort are repeated in LazyExpr; refactor
29772975
def indices(self, order: str | list[str] | None = None) -> blosc2.LazyArray:

src/blosc2/ndarray.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3717,8 +3717,8 @@ def _check_ndarray_kwargs(**kwargs): # noqa: C901
37173717
else:
37183718
# Add the default storage values as long as they are not already passed
37193719
storage_dflts = asdict(blosc2.Storage(urlpath=kwargs.get("urlpath"))) # urlpath can affect defaults
3720-
not_passed = {k: v for k, v in storage_dflts.items() if k not in kwargs}
3721-
kwargs = {**kwargs, **not_passed}
3720+
# If a key appears in both operands, the one from the right-hand operand wins
3721+
kwargs = storage_dflts | kwargs
37223722

37233723
supported_keys = [
37243724
"chunks",

src/blosc2/proxy.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -731,15 +731,11 @@ def apply(cls, data, func, args, kwargs, decorator, axis):
731731
return func(data, *args, **kwargs)
732732
elif axis in (0, "index"):
733733
# pandas apply(axis=0) column-wise
734-
result = []
735-
for row_idx in range(data.shape[1]):
736-
result.append(func(data[:, row_idx], *args, **kwargs))
734+
result = [func(data[:, row_idx], *args, **kwargs) for row_idx in range(data.shape[1])]
737735
return np.vstack(result).transpose()
738736
elif axis in (1, "columns"):
739737
# pandas apply(axis=1) row-wise
740-
result = []
741-
for col_idx in range(data.shape[0]):
742-
result.append(func(data[col_idx, :], *args, **kwargs))
738+
result = [func(data[col_idx, :], *args, **kwargs) for col_idx in range(data.shape[0])]
743739
return np.vstack(result)
744740
else:
745741
raise NotImplementedError(f"Unknown axis '{axis}'. Use one of 0, 1 or None.")

src/blosc2/schunk.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,7 @@ def __len__(self):
6868
return super().nvlmetalayers()
6969

7070
def __iter__(self):
71-
keys = super().get_names()
72-
yield from keys
71+
yield from super().get_names()
7372

7473
def getall(self):
7574
"""

tests/ndarray/test_lossy.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,10 @@ def test_lossy(shape, cparams, dtype, urlpath, contiguous):
7575
or a.schunk.cparams.filters[0] == blosc2.Filter.NDMEAN
7676
):
7777
_ = a[...]
78-
else:
78+
elif dtype in (np.float32, np.float64):
7979
tol = 1e-5
80-
if dtype in (np.float32, np.float64):
81-
np.testing.assert_allclose(a[...], array, rtol=tol, atol=tol)
82-
else:
83-
np.array_equal(a[...], array)
80+
np.testing.assert_allclose(a[...], array, rtol=tol, atol=tol)
81+
else:
82+
np.array_equal(a[...], array)
8483

8584
blosc2.remove_urlpath(urlpath)

tests/test_schunk_constructor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def test_schunk_fill_special(contiguous, urlpath, cparams, nitems, special_value
158158
if isinstance(expected_value, float):
159159
dtype = np.float32
160160
elif isinstance(expected_value, bytes):
161-
dtype = np.dtype("|S" + str(len(expected_value)))
161+
dtype = np.dtype(f"|S{len(expected_value)}")
162162
array = np.full(nitems, expected_value, dtype=dtype)
163163
dest = np.empty(nitems, dtype=dtype)
164164
schunk.get_slice(out=dest)

0 commit comments

Comments
 (0)