Skip to content

Commit b9780e7

Browse files
authored
Replace black and blackdoc with ruff-format (#9506)
* Replace black with ruff-format * Fix formatting mistakes moving mypy comments * Replace black with ruff in the contributing guides
1 parent 1e579fb commit b9780e7

33 files changed

+41
-70
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,20 +15,15 @@ repos:
1515
# Ruff version.
1616
rev: 'v0.6.9'
1717
hooks:
18+
- id: ruff-format
1819
- id: ruff
1920
args: ["--fix", "--show-fixes"]
20-
# https://github.com/python/black#version-control-integration
21-
- repo: https://github.com/psf/black-pre-commit-mirror
22-
rev: 24.8.0
23-
hooks:
24-
- id: black-jupyter
2521
- repo: https://github.com/keewis/blackdoc
2622
rev: v0.3.9
2723
hooks:
2824
- id: blackdoc
2925
exclude: "generate_aggregations.py"
3026
additional_dependencies: ["black==24.8.0"]
31-
- id: blackdoc-autoupdate-black
3227
- repo: https://github.com/pre-commit/mirrors-mypy
3328
rev: v1.11.2
3429
hooks:

CORE_TEAM_GUIDE.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -271,8 +271,7 @@ resources such as:
271271
[NumPy documentation guide](https://numpy.org/devdocs/dev/howto-docs.html#documentation-style)
272272
for docstring conventions.
273273
- [`pre-commit`](https://pre-commit.com) hooks for autoformatting.
274-
- [`black`](https://github.com/psf/black) autoformatting.
275-
- [`flake8`](https://github.com/PyCQA/flake8) linting.
274+
- [`ruff`](https://github.com/astral-sh/ruff) autoformatting and linting.
276275
- [python-xarray](https://stackoverflow.com/questions/tagged/python-xarray) on Stack Overflow.
277276
- [@xarray_dev](https://twitter.com/xarray_dev) on Twitter.
278277
- [xarray-dev](https://discord.gg/bsSGdwBn) discord community (normally only used for remote synchronous chat during sprints).

ci/min_deps_check.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
publication date. Compare it against requirements/min-all-deps.yml to verify the
44
policy on obsolete dependencies is being followed. Print a pretty report :)
55
"""
6+
67
from __future__ import annotations
78

89
import itertools
@@ -16,7 +17,6 @@
1617

1718
CHANNELS = ["conda-forge", "defaults"]
1819
IGNORE_DEPS = {
19-
"black",
2020
"coveralls",
2121
"flake8",
2222
"hypothesis",

ci/requirements/all-but-dask.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ channels:
33
- conda-forge
44
- nodefaults
55
dependencies:
6-
- black
76
- aiobotocore
87
- array-api-strict
98
- boto3

doc/contributing.rst

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -549,11 +549,7 @@ Code Formatting
549549

550550
xarray uses several tools to ensure a consistent code format throughout the project:
551551

552-
- `Black <https://black.readthedocs.io/en/stable/>`_ for standardized
553-
code formatting,
554-
- `blackdoc <https://blackdoc.readthedocs.io/en/stable/>`_ for
555-
standardized code formatting in documentation,
556-
- `ruff <https://github.com/charliermarsh/ruff/>`_ for code quality checks and standardized order in imports
552+
- `ruff <https://github.com/astral-sh/ruff>`_ for formatting, code quality checks and standardized order in imports
557553
- `absolufy-imports <https://github.com/MarcoGorelli/absolufy-imports>`_ for absolute instead of relative imports from different files,
558554
- `mypy <http://mypy-lang.org/>`_ for static type checking on `type hints
559555
<https://docs.python.org/3/library/typing.html>`_.
@@ -1069,7 +1065,7 @@ PR checklist
10691065
- Test the code using `Pytest <http://doc.pytest.org/en/latest/>`_. Running all tests (type ``pytest`` in the root directory) takes a while, so feel free to only run the tests you think are needed based on your PR (example: ``pytest xarray/tests/test_dataarray.py``). CI will catch any failing tests.
10701066
- By default, the upstream dev CI is disabled on pull request and push events. You can override this behavior per commit by adding a ``[test-upstream]`` tag to the first line of the commit message. For documentation-only commits, you can skip the CI per commit by adding a ``[skip-ci]`` tag to the first line of the commit message.
10711067
1072-
- **Properly format your code** and verify that it passes the formatting guidelines set by `Black <https://black.readthedocs.io/en/stable/>`_ and `Flake8 <http://flake8.pycqa.org/en/latest/>`_. See `"Code formatting" <https://docs.xarray.dev/en/stablcontributing.html#code-formatting>`_. You can use `pre-commit <https://pre-commit.com/>`_ to run these automatically on each commit.
1068+
- **Properly format your code** and verify that it passes the formatting guidelines set by `ruff <https://github.com/astral-sh/ruff>`_. See `"Code formatting" <https://docs.xarray.dev/en/stablcontributing.html#code-formatting>`_. You can use `pre-commit <https://pre-commit.com/>`_ to run these automatically on each commit.
10731069
10741070
- Run ``pre-commit run --all-files`` in the root directory. This may modify some files. Confirm and commit any formatting changes.
10751071

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ extend-exclude = [
233233

234234
[tool.ruff.lint]
235235
# E402: module level import not at top of file
236-
# E501: line too long - let black worry about that
236+
# E501: line too long - let the formatter worry about that
237237
# E731: do not assign a lambda expression, use a def
238238
extend-safe-fixes = [
239239
"TID252", # absolute imports

xarray/backends/common.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -206,13 +206,10 @@ def load(self):
206206
For example::
207207
208208
class SuffixAppendingDataStore(AbstractDataStore):
209-
210209
def load(self):
211210
variables, attributes = AbstractDataStore.load(self)
212-
variables = {'%s_suffix' % k: v
213-
for k, v in variables.items()}
214-
attributes = {'%s_suffix' % k: v
215-
for k, v in attributes.items()}
211+
variables = {"%s_suffix" % k: v for k, v in variables.items()}
212+
attributes = {"%s_suffix" % k: v for k, v in attributes.items()}
216213
return variables, attributes
217214
218215
This function will be called anytime variables or attributes

xarray/backends/file_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ class CachingFileManager(FileManager):
6565
6666
Example usage::
6767
68-
manager = FileManager(open, 'example.txt', mode='w')
68+
manager = FileManager(open, "example.txt", mode="w")
6969
f = manager.acquire()
7070
f.write(...)
7171
manager.close() # ensures file is closed

xarray/backends/h5netcdf_.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,6 @@ def open_datatree(
474474
driver_kwds=None,
475475
**kwargs,
476476
) -> DataTree:
477-
478477
from xarray.core.datatree import DataTree
479478

480479
groups_dict = self.open_groups_as_dict(
@@ -520,7 +519,6 @@ def open_groups_as_dict(
520519
driver_kwds=None,
521520
**kwargs,
522521
) -> dict[str, Dataset]:
523-
524522
from xarray.backends.common import _iter_nc_groups
525523
from xarray.core.treenode import NodePath
526524
from xarray.core.utils import close_on_error

xarray/backends/netCDF4_.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -710,7 +710,6 @@ def open_datatree(
710710
autoclose=False,
711711
**kwargs,
712712
) -> DataTree:
713-
714713
from xarray.core.datatree import DataTree
715714

716715
groups_dict = self.open_groups_as_dict(

xarray/backends/plugins.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def backends_dict_from_pkg(
8080

8181

8282
def set_missing_parameters(
83-
backend_entrypoints: dict[str, type[BackendEntrypoint]]
83+
backend_entrypoints: dict[str, type[BackendEntrypoint]],
8484
) -> None:
8585
for _, backend in backend_entrypoints.items():
8686
if backend.open_dataset_parameters is None:
@@ -89,7 +89,7 @@ def set_missing_parameters(
8989

9090

9191
def sort_backends(
92-
backend_entrypoints: dict[str, type[BackendEntrypoint]]
92+
backend_entrypoints: dict[str, type[BackendEntrypoint]],
9393
) -> dict[str, type[BackendEntrypoint]]:
9494
ordered_backends_entrypoints = {}
9595
for be_name in STANDARD_BACKENDS_ORDER:

xarray/backends/zarr.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,6 @@ def open_store(
496496
zarr_version=None,
497497
write_empty: bool | None = None,
498498
):
499-
500499
zarr_group, consolidate_on_close, close_store_on_close = _get_open_params(
501500
store=store,
502501
mode=mode,
@@ -542,7 +541,6 @@ def open_group(
542541
zarr_version=None,
543542
write_empty: bool | None = None,
544543
):
545-
546544
zarr_group, consolidate_on_close, close_store_on_close = _get_open_params(
547545
store=store,
548546
mode=mode,
@@ -1338,7 +1336,6 @@ def open_groups_as_dict(
13381336
zarr_version=None,
13391337
**kwargs,
13401338
) -> dict[str, Dataset]:
1341-
13421339
from xarray.core.treenode import NodePath
13431340

13441341
filename_or_obj = _normalize_path(filename_or_obj)
@@ -1385,7 +1382,6 @@ def open_groups_as_dict(
13851382

13861383

13871384
def _iter_zarr_groups(root: ZarrGroup, parent: str = "/") -> Iterable[str]:
1388-
13891385
parent_nodepath = NodePath(parent)
13901386
yield str(parent_nodepath)
13911387
for path, group in root.groups():

xarray/convert.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
"""Functions for converting to and from xarray objects
2-
"""
1+
"""Functions for converting to and from xarray objects"""
32

43
from collections import Counter
54

xarray/core/dataarray.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1582,7 +1582,7 @@ def sel(
15821582
Do not try to assign values when using any of the indexing methods
15831583
``isel`` or ``sel``::
15841584
1585-
da = xr.DataArray([0, 1, 2, 3], dims=['x'])
1585+
da = xr.DataArray([0, 1, 2, 3], dims=["x"])
15861586
# DO NOT do this
15871587
da.isel(x=[0, 1, 2])[1] = -1
15881588

xarray/core/datatree.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -801,7 +801,6 @@ def _replace_node(
801801
data: Dataset | Default = _default,
802802
children: dict[str, DataTree] | Default = _default,
803803
) -> None:
804-
805804
ds = self.to_dataset(inherit=False) if data is _default else data
806805

807806
if children is _default:

xarray/core/formatting.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
"""String formatting routines for __repr__.
2-
"""
1+
"""String formatting routines for __repr__."""
32

43
from __future__ import annotations
54

xarray/core/groupby.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,9 @@ def to_array(self) -> DataArray:
235235
T_Group = Union["T_DataArray", _DummyGroup]
236236

237237

238-
def _ensure_1d(group: T_Group, obj: T_DataWithCoords) -> tuple[
238+
def _ensure_1d(
239+
group: T_Group, obj: T_DataWithCoords
240+
) -> tuple[
239241
T_Group,
240242
T_DataWithCoords,
241243
Hashable | None,
@@ -462,7 +464,10 @@ def factorize(self) -> EncodedGroups:
462464
)
463465
# NaNs; as well as values outside the bins are coded by -1
464466
# Restore these after the raveling
465-
mask = functools.reduce(np.logical_or, [(code == -1) for code in broadcasted_codes]) # type: ignore[arg-type]
467+
mask = functools.reduce(
468+
np.logical_or, # type: ignore[arg-type]
469+
[(code == -1) for code in broadcasted_codes],
470+
)
466471
_flatcodes[mask] = -1
467472

468473
midx = pd.MultiIndex.from_product(
@@ -1288,7 +1293,6 @@ def _concat_shortcut(self, applied, dim, positions=None):
12881293
return self._obj._replace_maybe_drop_dims(reordered)
12891294

12901295
def _restore_dim_order(self, stacked: DataArray) -> DataArray:
1291-
12921296
def lookup_order(dimension):
12931297
for grouper in self.groupers:
12941298
if dimension == grouper.name and grouper.group.ndim == 1:

xarray/core/indexes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1768,7 +1768,7 @@ def indexes_equal(
17681768

17691769

17701770
def indexes_all_equal(
1771-
elements: Sequence[tuple[Index, dict[Hashable, Variable]]]
1771+
elements: Sequence[tuple[Index, dict[Hashable, Variable]]],
17721772
) -> bool:
17731773
"""Check if indexes are all equal.
17741774

xarray/core/parallel.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -372,7 +372,8 @@ def _wrapper(
372372

373373
# ChainMap wants MutableMapping, but xindexes is Mapping
374374
merged_indexes = collections.ChainMap(
375-
expected["indexes"], merged_coordinates.xindexes # type: ignore[arg-type]
375+
expected["indexes"],
376+
merged_coordinates.xindexes, # type: ignore[arg-type]
376377
)
377378
expected_index = merged_indexes.get(name, None)
378379
if expected_index is not None and not index.equals(expected_index):

xarray/core/resample.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,9 @@ def _interpolate(self, kind="linear", **kwargs) -> T_Xarray:
188188

189189

190190
# https://github.com/python/mypy/issues/9031
191-
class DataArrayResample(Resample["DataArray"], DataArrayGroupByBase, DataArrayResampleAggregations): # type: ignore[misc]
191+
class DataArrayResample( # type: ignore[misc]
192+
Resample["DataArray"], DataArrayGroupByBase, DataArrayResampleAggregations
193+
):
192194
"""DataArrayGroupBy object specialized to time resampling operations over a
193195
specified dimension
194196
"""
@@ -329,7 +331,9 @@ def asfreq(self) -> DataArray:
329331

330332

331333
# https://github.com/python/mypy/issues/9031
332-
class DatasetResample(Resample["Dataset"], DatasetGroupByBase, DatasetResampleAggregations): # type: ignore[misc]
334+
class DatasetResample( # type: ignore[misc]
335+
Resample["Dataset"], DatasetGroupByBase, DatasetResampleAggregations
336+
):
333337
"""DatasetGroupBy object specialized to resampling a specified dimension"""
334338

335339
def map(

xarray/core/variable.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -839,7 +839,6 @@ def _getitem_with_mask(self, key, fill_value=dtypes.NA):
839839
dims, indexer, new_order = self._broadcast_indexes(key)
840840

841841
if self.size:
842-
843842
if is_duck_dask_array(self._data):
844843
# dask's indexing is faster this way; also vindex does not
845844
# support negative indices yet:

xarray/namedarray/_array_api.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ def astype(
7979

8080

8181
def imag(
82-
x: NamedArray[_ShapeType, np.dtype[_SupportsImag[_ScalarType]]], / # type: ignore[type-var]
82+
x: NamedArray[_ShapeType, np.dtype[_SupportsImag[_ScalarType]]], # type: ignore[type-var]
83+
/,
8384
) -> NamedArray[_ShapeType, np.dtype[_ScalarType]]:
8485
"""
8586
Returns the imaginary component of a complex number for each element x_i of the
@@ -111,7 +112,8 @@ def imag(
111112

112113

113114
def real(
114-
x: NamedArray[_ShapeType, np.dtype[_SupportsReal[_ScalarType]]], / # type: ignore[type-var]
115+
x: NamedArray[_ShapeType, np.dtype[_SupportsReal[_ScalarType]]], # type: ignore[type-var]
116+
/,
115117
) -> NamedArray[_ShapeType, np.dtype[_ScalarType]]:
116118
"""
117119
Returns the real component of a complex number for each element x_i of the

xarray/plot/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -986,7 +986,7 @@ def legend_elements(
986986
This is useful for obtaining a legend for a `~.Axes.scatter` plot;
987987
e.g.::
988988
989-
scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3])
989+
scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3])
990990
plt.legend(*scatter.legend_elements())
991991
992992
creates three legend elements, one for each color with the numerical

xarray/tests/test_cftime_offsets.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1673,7 +1673,6 @@ def test_new_to_legacy_freq_anchored(year_alias, n):
16731673
),
16741674
)
16751675
def test_legacy_to_new_freq_pd_freq_passthrough(freq, expected):
1676-
16771676
result = _legacy_to_new_freq(freq)
16781677
assert result == expected
16791678

@@ -1699,7 +1698,6 @@ def test_legacy_to_new_freq_pd_freq_passthrough(freq, expected):
16991698
),
17001699
)
17011700
def test_new_to_legacy_freq_pd_freq_passthrough(freq, expected):
1702-
17031701
result = _new_to_legacy_freq(freq)
17041702
assert result == expected
17051703

@@ -1786,7 +1784,6 @@ def test_date_range_no_freq(start, end, periods):
17861784
)
17871785
@pytest.mark.parametrize("has_year_zero", [False, True])
17881786
def test_offset_addition_preserves_has_year_zero(offset, has_year_zero):
1789-
17901787
with warnings.catch_warnings():
17911788
warnings.filterwarnings("ignore", message="this date/calendar/year zero")
17921789
datetime = cftime.DatetimeGregorian(-1, 12, 31, has_year_zero=has_year_zero)

xarray/tests/test_coordinates.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,10 @@ def test_init_index_error(self) -> None:
6464
Coordinates(indexes={"x": idx})
6565

6666
with pytest.raises(TypeError, match=".* is not an `xarray.indexes.Index`"):
67-
Coordinates(coords={"x": ("x", [1, 2, 3])}, indexes={"x": "not_an_xarray_index"}) # type: ignore[dict-item]
67+
Coordinates(
68+
coords={"x": ("x", [1, 2, 3])},
69+
indexes={"x": "not_an_xarray_index"}, # type: ignore[dict-item]
70+
)
6871

6972
def test_init_dim_sizes_conflict(self) -> None:
7073
with pytest.raises(ValueError):

xarray/tests/test_dataset.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -297,9 +297,7 @@ def test_repr(self) -> None:
297297
var2 (dim1, dim2) float64 576B 1.162 -1.097 -2.123 ... 1.267 0.3328
298298
var3 (dim3, dim1) float64 640B 0.5565 -0.2121 0.4563 ... -0.2452 -0.3616
299299
Attributes:
300-
foo: bar""".format(
301-
data["dim3"].dtype
302-
)
300+
foo: bar""".format(data["dim3"].dtype)
303301
)
304302
actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))
305303
print(actual)

0 commit comments

Comments
 (0)