Skip to content

Commit

Permalink
Update pre-commit hooks (#10021)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
pre-commit-ci[bot] authored Feb 3, 2025
1 parent c252152 commit d924d93
Show file tree
Hide file tree
Showing 20 changed files with 56 additions and 65 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ repos:
- id: text-unicode-replacement-char
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.8.6
rev: v0.9.4
hooks:
- id: ruff-format
- id: ruff
Expand Down
6 changes: 2 additions & 4 deletions xarray/backends/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ def _get_default_engine_remote_uri() -> Literal["netcdf4", "pydap"]:
engine = "pydap"
except ImportError as err:
raise ValueError(
"netCDF4 or pydap is required for accessing "
"remote datasets via OPeNDAP"
"netCDF4 or pydap is required for accessing remote datasets via OPeNDAP"
) from err
return engine

Expand Down Expand Up @@ -1669,8 +1668,7 @@ def open_mfdataset(
)
else:
raise ValueError(
f"{combine} is an invalid option for the keyword argument"
" ``combine``"
f"{combine} is an invalid option for the keyword argument ``combine``"
)
except ValueError:
for ds in datasets:
Expand Down
3 changes: 1 addition & 2 deletions xarray/backends/h5netcdf_.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,7 @@ def __init__(self, manager, group=None, mode=None, lock=HDF5_LOCK, autoclose=Fal
else:
if type(manager) is not h5netcdf.File:
raise ValueError(
"must supply a h5netcdf.File if the group "
"argument is provided"
"must supply a h5netcdf.File if the group argument is provided"
)
root = manager
manager = DummyFileManager(root)
Expand Down
8 changes: 5 additions & 3 deletions xarray/coding/cftimeindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,16 +294,18 @@ def __repr__(self):
offset=offset,
first_row_offset=offset,
)
datastr = "\n".join([front_str, f"{' '*offset}...", end_str])
datastr = "\n".join([front_str, f"{' ' * offset}...", end_str])

attrs_str = format_attrs(self)
# oneliner only if smaller than display_width
full_repr_str = f"{klass_name}([{datastr}], {attrs_str})"
if len(full_repr_str) > display_width:
# if attrs_str too long, one per line
if len(attrs_str) >= display_width - offset:
attrs_str = attrs_str.replace(",", f",\n{' '*(offset-2)}")
full_repr_str = f"{klass_name}([{datastr}],\n{' '*(offset-1)}{attrs_str})"
attrs_str = attrs_str.replace(",", f",\n{' ' * (offset - 2)}")
full_repr_str = (
f"{klass_name}([{datastr}],\n{' ' * (offset - 1)}{attrs_str})"
)

return full_repr_str

Expand Down
3 changes: 1 addition & 2 deletions xarray/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,8 +412,7 @@ def get_squeeze_dims(

if any(xarray_obj.sizes[k] > 1 for k in dim):
raise ValueError(
"cannot select a dimension to squeeze out "
"which has length greater than one"
"cannot select a dimension to squeeze out which has length greater than one"
)
return dim

Expand Down
6 changes: 2 additions & 4 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -3512,8 +3512,7 @@ def fillna(self, value: Any) -> Self:
"""
if utils.is_dict_like(value):
raise TypeError(
"cannot provide fill value as a dictionary with "
"fillna on a DataArray"
"cannot provide fill value as a dictionary with fillna on a DataArray"
)
out = ops.fillna(self, value)
return out
Expand Down Expand Up @@ -4537,8 +4536,7 @@ def from_dict(cls, d: Mapping[str, Any]) -> Self:
}
except KeyError as e:
raise ValueError(
"cannot convert dict when coords are missing the key "
f"'{e.args[0]}'"
f"cannot convert dict when coords are missing the key '{e.args[0]}'"
) from e
try:
data = d["data"]
Expand Down
2 changes: 1 addition & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -6478,7 +6478,7 @@ def transpose(
if (len(dim) > 0) and (isinstance(dim[0], list)):
list_fix = [f"{x!r}" if isinstance(x, str) else f"{x}" for x in dim[0]]
raise TypeError(
f'transpose requires dim to be passed as multiple arguments. Expected `{", ".join(list_fix)}`. Received `{dim[0]}` instead'
f"transpose requires dim to be passed as multiple arguments. Expected `{', '.join(list_fix)}`. Received `{dim[0]}` instead"
)

# Use infix_dims to check once for missing dimensions
Expand Down
3 changes: 1 addition & 2 deletions xarray/core/datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,8 +276,7 @@ def set_close(self, close: Callable[[], None] | None) -> None:

def close(self) -> None:
raise AttributeError(
"cannot close a DatasetView(). Close the associated DataTree node "
"instead"
"cannot close a DatasetView(). Close the associated DataTree node instead"
)

# FIXME https://github.com/python/mypy/issues/7328
Expand Down
6 changes: 3 additions & 3 deletions xarray/core/datatree_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ def __init__(self, vertical: str, cont: str, end: str):
self.vertical = vertical
self.cont = cont
self.end = end
assert (
len(cont) == len(vertical) == len(end)
), f"'{vertical}', '{cont}' and '{end}' need to have equal length"
assert len(cont) == len(vertical) == len(end), (
f"'{vertical}', '{cont}' and '{end}' need to have equal length"
)

@property
def empty(self) -> str:
Expand Down
5 changes: 1 addition & 4 deletions xarray/core/formatting_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,7 @@ def summarize_attrs(attrs) -> str:
def _icon(icon_name) -> str:
# icon_name should be defined in xarray/static/html/icon-svg-inline.html
return (
f"<svg class='icon xr-{icon_name}'>"
f"<use xlink:href='#{icon_name}'>"
"</use>"
"</svg>"
f"<svg class='icon xr-{icon_name}'><use xlink:href='#{icon_name}'></use></svg>"
)


Expand Down
6 changes: 3 additions & 3 deletions xarray/core/treenode.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,9 @@ def _attach(self, parent: Tree | None, child_name: str | None = None) -> None:

self._pre_attach(parent, child_name)
parentchildren = parent._children
assert not any(
child is self for child in parentchildren
), "Tree is corrupt."
assert not any(child is self for child in parentchildren), (
"Tree is corrupt."
)
parentchildren[child_name] = self
self._parent = parent
self._post_attach(parent, child_name)
Expand Down
3 changes: 1 addition & 2 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,8 +651,7 @@ def _validate_indexers(self, key):
)
if k.ndim > 1:
raise IndexError(
f"{k.ndim}-dimensional boolean indexing is "
"not supported. "
f"{k.ndim}-dimensional boolean indexing is not supported. "
)
if is_duck_dask_array(k.data):
raise KeyError(
Expand Down
6 changes: 3 additions & 3 deletions xarray/testing/assertions.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,9 @@ def assert_identical(a, b):
if isinstance(a, Variable):
assert a.identical(b), formatting.diff_array_repr(a, b, "identical")
elif isinstance(a, DataArray):
assert (
a.name == b.name
), f"DataArray names are different. L: {a.name}, R: {b.name}"
assert a.name == b.name, (
f"DataArray names are different. L: {a.name}, R: {b.name}"
)
assert a.identical(b), formatting.diff_array_repr(a, b, "identical")
elif isinstance(a, Dataset | Variable):
assert a.identical(b), formatting.diff_dataset_repr(a, b, "identical")
Expand Down
8 changes: 4 additions & 4 deletions xarray/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,9 +269,9 @@ def format_record(record) -> str:
def assert_no_warnings():
with warnings.catch_warnings(record=True) as record:
yield record
assert (
len(record) == 0
), f"Got {len(record)} unexpected warning(s): {[format_record(r) for r in record]}"
assert len(record) == 0, (
f"Got {len(record)} unexpected warning(s): {[format_record(r) for r in record]}"
)


# Internal versions of xarray's test functions that validate additional
Expand Down Expand Up @@ -320,7 +320,7 @@ def create_test_data(
obj["dim2"] = ("dim2", 0.5 * np.arange(_dims["dim2"]))
if _dims["dim3"] > 26:
raise RuntimeError(
f'Not enough letters for filling this dimension size ({_dims["dim3"]})'
f"Not enough letters for filling this dimension size ({_dims['dim3']})"
)
obj["dim3"] = ("dim3", list(string.ascii_lowercase[0 : _dims["dim3"]]))
obj["time"] = (
Expand Down
12 changes: 6 additions & 6 deletions xarray/tests/test_backends_datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,9 +301,9 @@ def test_open_groups_chunks(self, tmpdir) -> None:
dict_of_datasets = open_groups(filepath, engine="netcdf4", chunks=chunks)

for path, ds in dict_of_datasets.items():
assert {
k: max(vs) for k, vs in ds.chunksizes.items()
} == chunks, f"unexpected chunking for {path}"
assert {k: max(vs) for k, vs in ds.chunksizes.items()} == chunks, (
f"unexpected chunking for {path}"
)

for ds in dict_of_datasets.values():
ds.close()
Expand Down Expand Up @@ -587,9 +587,9 @@ def test_open_groups_chunks(self, tmpdir) -> None:
dict_of_datasets = open_groups(filepath, engine="zarr", chunks=chunks)

for path, ds in dict_of_datasets.items():
assert {
k: max(vs) for k, vs in ds.chunksizes.items()
} == chunks, f"unexpected chunking for {path}"
assert {k: max(vs) for k, vs in ds.chunksizes.items()} == chunks, (
f"unexpected chunking for {path}"
)

for ds in dict_of_datasets.values():
ds.close()
Expand Down
12 changes: 6 additions & 6 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -1792,12 +1792,12 @@ def test_reindex_empty_array_dtype(self) -> None:
x = xr.DataArray([], dims=("x",), coords={"x": []}).astype("float32")
y = x.reindex(x=[1.0, 2.0])

assert (
x.dtype == y.dtype
), "Dtype of reindexed DataArray should match dtype of the original DataArray"
assert (
y.dtype == np.float32
), "Dtype of reindexed DataArray should remain float32"
assert x.dtype == y.dtype, (
"Dtype of reindexed DataArray should match dtype of the original DataArray"
)
assert y.dtype == np.float32, (
"Dtype of reindexed DataArray should remain float32"
)

def test_rename(self) -> None:
da = xr.DataArray(
Expand Down
2 changes: 1 addition & 1 deletion xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ def test_unicode_data(self) -> None:
<xarray.Dataset> Size: 12B
Dimensions: (foø: 1)
Coordinates:
* foø (foø) {byteorder}U3 12B {'ba®'!r}
* foø (foø) {byteorder}U3 12B {"ba®"!r}
Data variables:
*empty*
Attributes:
Expand Down
18 changes: 9 additions & 9 deletions xarray/tests/test_datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -2338,15 +2338,15 @@ def fn(x):
assert_identical(actual, expected)

assert actual.chunksizes == original_chunksizes, "chunksizes were modified"
assert (
tree.chunksizes == original_chunksizes
), "original chunksizes were modified"
assert all(
d == 1 for d in actual_hlg_depths.values()
), "unexpected dask graph depth"
assert all(
d == 2 for d in original_hlg_depths.values()
), "original dask graph was modified"
assert tree.chunksizes == original_chunksizes, (
"original chunksizes were modified"
)
assert all(d == 1 for d in actual_hlg_depths.values()), (
"unexpected dask graph depth"
)
assert all(d == 2 for d in original_hlg_depths.values()), (
"original dask graph was modified"
)

def test_chunk(self):
ds1 = xr.Dataset({"a": ("x", np.arange(10))})
Expand Down
6 changes: 3 additions & 3 deletions xarray/tests/test_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,9 @@ def test_lazy_import() -> None:
if pkg.startswith(mod):
is_imported.add(mod)
break
assert (
len(is_imported) == 0
), f"{is_imported} have been imported but should be lazy"
assert len(is_imported) == 0, (
f"{is_imported} have been imported but should be lazy"
)

finally:
# restore original
Expand Down
4 changes: 2 additions & 2 deletions xarray/util/print_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ def get_sys_info():
("machine", f"{machine}"),
("processor", f"{processor}"),
("byteorder", f"{sys.byteorder}"),
("LC_ALL", f'{os.environ.get("LC_ALL", "None")}'),
("LANG", f'{os.environ.get("LANG", "None")}'),
("LC_ALL", f"{os.environ.get('LC_ALL', 'None')}"),
("LANG", f"{os.environ.get('LANG', 'None')}"),
("LOCALE", f"{locale.getlocale()}"),
]
)
Expand Down

0 comments on commit d924d93

Please sign in to comment.