Skip to content

Commit 176c6eb

Browse files
max-sixtypre-commit-ci[bot]Illviljan
authored
Add pyupgrade onto pre-commit (#6152)
* Add pyupgrade onto pre-commit * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update doc/whats-new.rst Co-authored-by: Illviljan <[email protected]> * . Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Illviljan <[email protected]>
1 parent 84961e6 commit 176c6eb

29 files changed

+631
-695
lines changed

.pre-commit-config.yaml

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,24 @@ repos:
66
- id: trailing-whitespace
77
- id: end-of-file-fixer
88
- id: check-yaml
9-
# isort should run before black as black sometimes tweaks the isort output
9+
- id: debug-statements
10+
- id: mixed-line-ending
11+
# This wants to go before isort & flake8
12+
- repo: https://github.com/myint/autoflake
13+
rev: "v1.4"
14+
hooks:
15+
- id: autoflake # isort should run before black as black sometimes tweaks the isort output
16+
args: ["--in-place", "--ignore-init-module-imports"]
1017
- repo: https://github.com/PyCQA/isort
1118
rev: 5.10.1
1219
hooks:
1320
- id: isort
21+
- repo: https://github.com/asottile/pyupgrade
22+
rev: v2.31.0
23+
hooks:
24+
- id: pyupgrade
25+
args:
26+
- "--py37-plus"
1427
# https://github.com/python/black#version-control-integration
1528
- repo: https://github.com/psf/black
1629
rev: 21.12b0
@@ -47,12 +60,3 @@ repos:
4760
typing-extensions==3.10.0.0,
4861
numpy,
4962
]
50-
# run this occasionally, ref discussion https://github.com/pydata/xarray/pull/3194
51-
# - repo: https://github.com/asottile/pyupgrade
52-
# rev: v1.22.1
53-
# hooks:
54-
# - id: pyupgrade
55-
# args:
56-
# - "--py3-only"
57-
# # remove on f-strings in Py3.7
58-
# - "--keep-percent-format"

doc/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ Internal Changes
7878
- Removed internal checks for ``pd.Panel`` (:issue:`6145`).
7979
By `Matthew Roeschke <https://github.com/mroeschke>`_.
8080

81+
- Add ``pyupgrade`` pre-commit hook (:pull:`6152`).
82+
By `Maximilian Roos <https://github.com/max-sixty>`_.
8183

8284
.. _whats-new.0.20.2:
8385

xarray/backends/plugins.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -168,10 +168,8 @@ def get_backend(engine):
168168
backend = engine()
169169
else:
170170
raise TypeError(
171-
(
172-
"engine must be a string or a subclass of "
173-
f"xarray.backends.BackendEntrypoint: {engine}"
174-
)
171+
"engine must be a string or a subclass of "
172+
f"xarray.backends.BackendEntrypoint: {engine}"
175173
)
176174

177175
return backend

xarray/coding/cftime_offsets.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def rollback(self, date):
160160
return date - type(self)()
161161

162162
def __str__(self):
163-
return "<{}: n={}>".format(type(self).__name__, self.n)
163+
return f"<{type(self).__name__}: n={self.n}>"
164164

165165
def __repr__(self):
166166
return str(self)
@@ -399,10 +399,10 @@ def __mul__(self, other):
399399
return type(self)(n=other * self.n, month=self.month)
400400

401401
def rule_code(self):
402-
return "{}-{}".format(self._freq, _MONTH_ABBREVIATIONS[self.month])
402+
return f"{self._freq}-{_MONTH_ABBREVIATIONS[self.month]}"
403403

404404
def __str__(self):
405-
return "<{}: n={}, month={}>".format(type(self).__name__, self.n, self.month)
405+
return f"<{type(self).__name__}: n={self.n}, month={self.month}>"
406406

407407

408408
class QuarterBegin(QuarterOffset):
@@ -485,10 +485,10 @@ def __mul__(self, other):
485485
return type(self)(n=other * self.n, month=self.month)
486486

487487
def rule_code(self):
488-
return "{}-{}".format(self._freq, _MONTH_ABBREVIATIONS[self.month])
488+
return f"{self._freq}-{_MONTH_ABBREVIATIONS[self.month]}"
489489

490490
def __str__(self):
491-
return "<{}: n={}, month={}>".format(type(self).__name__, self.n, self.month)
491+
return f"<{type(self).__name__}: n={self.n}, month={self.month}>"
492492

493493

494494
class YearBegin(YearOffset):
@@ -741,7 +741,7 @@ def _generate_linear_range(start, end, periods):
741741

742742
total_seconds = (end - start).total_seconds()
743743
values = np.linspace(0.0, total_seconds, periods, endpoint=True)
744-
units = "seconds since {}".format(format_cftime_datetime(start))
744+
units = f"seconds since {format_cftime_datetime(start)}"
745745
calendar = start.calendar
746746
return cftime.num2date(
747747
values, units=units, calendar=calendar, only_use_cftime_datetimes=True

xarray/coding/strings.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
def create_vlen_dtype(element_type):
2020
if element_type not in (str, bytes):
21-
raise TypeError("unsupported type for vlen_dtype: {!r}".format(element_type))
21+
raise TypeError(f"unsupported type for vlen_dtype: {element_type!r}")
2222
# based on h5py.special_dtype
2323
return np.dtype("O", metadata={"element_type": element_type})
2424

@@ -227,7 +227,7 @@ def shape(self):
227227
return self.array.shape[:-1]
228228

229229
def __repr__(self):
230-
return "{}({!r})".format(type(self).__name__, self.array)
230+
return f"{type(self).__name__}({self.array!r})"
231231

232232
def __getitem__(self, key):
233233
# require slicing the last dimension completely

xarray/coding/times.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,8 @@ def _ensure_padded_year(ref_date):
131131
matches_start_digits = re.match(r"(\d+)(.*)", ref_date)
132132
if not matches_start_digits:
133133
raise ValueError(f"invalid reference date for time units: {ref_date}")
134-
ref_year, everything_else = [s for s in matches_start_digits.groups()]
135-
ref_date_padded = "{:04d}{}".format(int(ref_year), everything_else)
134+
ref_year, everything_else = (s for s in matches_start_digits.groups())
135+
ref_date_padded = f"{int(ref_year):04d}{everything_else}"
136136

137137
warning_msg = (
138138
f"Ambiguous reference date string: {ref_date}. The first value is "
@@ -155,7 +155,7 @@ def _unpack_netcdf_time_units(units):
155155
if not matches:
156156
raise ValueError(f"invalid time units: {units}")
157157

158-
delta_units, ref_date = [s.strip() for s in matches.groups()]
158+
delta_units, ref_date = (s.strip() for s in matches.groups())
159159
ref_date = _ensure_padded_year(ref_date)
160160

161161
return delta_units, ref_date
@@ -545,7 +545,7 @@ def _should_cftime_be_used(source, target_calendar, use_cftime):
545545
def _cleanup_netcdf_time_units(units):
546546
delta, ref_date = _unpack_netcdf_time_units(units)
547547
try:
548-
units = "{} since {}".format(delta, format_timestamp(ref_date))
548+
units = f"{delta} since {format_timestamp(ref_date)}"
549549
except (OutOfBoundsDatetime, ValueError):
550550
# don't worry about reifying the units if they're out of bounds or
551551
# formatted badly

xarray/core/common.py

Lines changed: 28 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,11 @@
88
TYPE_CHECKING,
99
Any,
1010
Callable,
11-
Dict,
1211
Hashable,
1312
Iterable,
1413
Iterator,
15-
List,
1614
Mapping,
17-
Optional,
18-
Tuple,
1915
TypeVar,
20-
Union,
2116
overload,
2217
)
2318

@@ -164,9 +159,7 @@ def __iter__(self: Any) -> Iterator[Any]:
164159
raise TypeError("iteration over a 0-d array")
165160
return self._iter()
166161

167-
def get_axis_num(
168-
self, dim: Union[Hashable, Iterable[Hashable]]
169-
) -> Union[int, Tuple[int, ...]]:
162+
def get_axis_num(self, dim: Hashable | Iterable[Hashable]) -> int | tuple[int, ...]:
170163
"""Return axis number(s) corresponding to dimension(s) in this array.
171164
172165
Parameters
@@ -244,7 +237,7 @@ def __getattr__(self, name: str) -> Any:
244237
with suppress(KeyError):
245238
return source[name]
246239
raise AttributeError(
247-
"{!r} object has no attribute {!r}".format(type(self).__name__, name)
240+
f"{type(self).__name__!r} object has no attribute {name!r}"
248241
)
249242

250243
# This complicated two-method design boosts overall performance of simple operations
@@ -284,37 +277,37 @@ def __setattr__(self, name: str, value: Any) -> None:
284277
"assignment (e.g., `ds['name'] = ...`) instead of assigning variables."
285278
) from e
286279

287-
def __dir__(self) -> List[str]:
280+
def __dir__(self) -> list[str]:
288281
"""Provide method name lookup and completion. Only provide 'public'
289282
methods.
290283
"""
291-
extra_attrs = set(
284+
extra_attrs = {
292285
item
293286
for source in self._attr_sources
294287
for item in source
295288
if isinstance(item, str)
296-
)
289+
}
297290
return sorted(set(dir(type(self))) | extra_attrs)
298291

299-
def _ipython_key_completions_(self) -> List[str]:
292+
def _ipython_key_completions_(self) -> list[str]:
300293
"""Provide method for the key-autocompletions in IPython.
301294
See http://ipython.readthedocs.io/en/stable/config/integrating.html#tab-completion
302295
For the details.
303296
"""
304-
items = set(
297+
items = {
305298
item
306299
for source in self._item_sources
307300
for item in source
308301
if isinstance(item, str)
309-
)
302+
}
310303
return list(items)
311304

312305

313306
def get_squeeze_dims(
314307
xarray_obj,
315-
dim: Union[Hashable, Iterable[Hashable], None] = None,
316-
axis: Union[int, Iterable[int], None] = None,
317-
) -> List[Hashable]:
308+
dim: Hashable | Iterable[Hashable] | None = None,
309+
axis: int | Iterable[int] | None = None,
310+
) -> list[Hashable]:
318311
"""Get a list of dimensions to squeeze out."""
319312
if dim is not None and axis is not None:
320313
raise ValueError("cannot use both parameters `axis` and `dim`")
@@ -346,15 +339,15 @@ def get_squeeze_dims(
346339
class DataWithCoords(AttrAccessMixin):
347340
"""Shared base class for Dataset and DataArray."""
348341

349-
_close: Optional[Callable[[], None]]
342+
_close: Callable[[], None] | None
350343

351344
__slots__ = ("_close",)
352345

353346
def squeeze(
354347
self,
355-
dim: Union[Hashable, Iterable[Hashable], None] = None,
348+
dim: Hashable | Iterable[Hashable] | None = None,
356349
drop: bool = False,
357-
axis: Union[int, Iterable[int], None] = None,
350+
axis: int | Iterable[int] | None = None,
358351
):
359352
"""Return a new object with squeezed data.
360353
@@ -416,8 +409,8 @@ def get_index(self, key: Hashable) -> pd.Index:
416409
return pd.Index(range(self.sizes[key]), name=key)
417410

418411
def _calc_assign_results(
419-
self: C, kwargs: Mapping[Any, Union[T, Callable[[C], T]]]
420-
) -> Dict[Hashable, T]:
412+
self: C, kwargs: Mapping[Any, T | Callable[[C], T]]
413+
) -> dict[Hashable, T]:
421414
return {k: v(self) if callable(v) else v for k, v in kwargs.items()}
422415

423416
def assign_coords(self, coords=None, **coords_kwargs):
@@ -535,7 +528,7 @@ def assign_attrs(self, *args, **kwargs):
535528

536529
def pipe(
537530
self,
538-
func: Union[Callable[..., T], Tuple[Callable[..., T], str]],
531+
func: Callable[..., T] | tuple[Callable[..., T], str],
539532
*args,
540533
**kwargs,
541534
) -> T:
@@ -802,7 +795,7 @@ def groupby_bins(
802795
},
803796
)
804797

805-
def weighted(self: T_DataWithCoords, weights: "DataArray") -> Weighted[T_Xarray]:
798+
def weighted(self: T_DataWithCoords, weights: DataArray) -> Weighted[T_Xarray]:
806799
"""
807800
Weighted operations.
808801
@@ -825,7 +818,7 @@ def rolling(
825818
self,
826819
dim: Mapping[Any, int] = None,
827820
min_periods: int = None,
828-
center: Union[bool, Mapping[Any, bool]] = False,
821+
center: bool | Mapping[Any, bool] = False,
829822
**window_kwargs: int,
830823
):
831824
"""
@@ -940,7 +933,7 @@ def coarsen(
940933
self,
941934
dim: Mapping[Any, int] = None,
942935
boundary: str = "exact",
943-
side: Union[str, Mapping[Any, str]] = "left",
936+
side: str | Mapping[Any, str] = "left",
944937
coord_func: str = "mean",
945938
**window_kwargs: int,
946939
):
@@ -1290,7 +1283,7 @@ def where(self, cond, other=dtypes.NA, drop: bool = False):
12901283

12911284
return ops.where_method(self, cond, other)
12921285

1293-
def set_close(self, close: Optional[Callable[[], None]]) -> None:
1286+
def set_close(self, close: Callable[[], None] | None) -> None:
12941287
"""Register the function that releases any resources linked to this object.
12951288
12961289
This method controls how xarray cleans up resources associated
@@ -1523,20 +1516,20 @@ def __getitem__(self, value):
15231516

15241517
@overload
15251518
def full_like(
1526-
other: "Dataset",
1519+
other: Dataset,
15271520
fill_value,
1528-
dtype: Union[DTypeLike, Mapping[Any, DTypeLike]] = None,
1529-
) -> "Dataset":
1521+
dtype: DTypeLike | Mapping[Any, DTypeLike] = None,
1522+
) -> Dataset:
15301523
...
15311524

15321525

15331526
@overload
1534-
def full_like(other: "DataArray", fill_value, dtype: DTypeLike = None) -> "DataArray":
1527+
def full_like(other: DataArray, fill_value, dtype: DTypeLike = None) -> DataArray:
15351528
...
15361529

15371530

15381531
@overload
1539-
def full_like(other: "Variable", fill_value, dtype: DTypeLike = None) -> "Variable":
1532+
def full_like(other: Variable, fill_value, dtype: DTypeLike = None) -> Variable:
15401533
...
15411534

15421535

@@ -1815,9 +1808,9 @@ def ones_like(other, dtype: DTypeLike = None):
18151808

18161809
def get_chunksizes(
18171810
variables: Iterable[Variable],
1818-
) -> Mapping[Any, Tuple[int, ...]]:
1811+
) -> Mapping[Any, tuple[int, ...]]:
18191812

1820-
chunks: Dict[Any, Tuple[int, ...]] = {}
1813+
chunks: dict[Any, tuple[int, ...]] = {}
18211814
for v in variables:
18221815
if hasattr(v.data, "chunks"):
18231816
for dim, c in v.chunksizes.items():

0 commit comments

Comments
 (0)