Skip to content

Commit 3c462b9

Browse files
max-sixtycrusaderky
andcommitted
Python3.6 idioms (#3419)
* pyupgrade --py36-plus * Update xarray/core/nputils.py Co-Authored-By: crusaderky <[email protected]> * Update xarray/core/parallel.py Co-Authored-By: crusaderky <[email protected]> * Update xarray/tests/test_cftime_offsets.py Co-Authored-By: crusaderky <[email protected]> * Update xarray/tests/test_cftime_offsets.py Co-Authored-By: crusaderky <[email protected]>
1 parent 9886e3c commit 3c462b9

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+200
-221
lines changed

doc/gallery/plot_cartopy_facetgrid.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
==================================
43
Multiple plots and map projections

doc/gallery/plot_colorbar_center.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
==================
43
Centered colormaps

doc/gallery/plot_control_colorbar.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
===========================
43
Control the plot's colorbar

doc/gallery/plot_lines_from_2d.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
==================================
43
Multiple lines from a 2d DataArray

doc/gallery/plot_rasterio.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
.. _recipes.rasterio:
43

doc/gallery/plot_rasterio_rgb.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
.. _recipes.rasterio_rgb:
43

xarray/_version.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=
9494
return None, None
9595
else:
9696
if verbose:
97-
print("unable to find command, tried %s" % (commands,))
97+
print(f"unable to find command, tried {commands}")
9898
return None, None
9999
stdout = p.communicate()[0].strip()
100100
if sys.version_info[0] >= 3:
@@ -302,9 +302,8 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
302302
if verbose:
303303
fmt = "tag '%s' doesn't start with prefix '%s'"
304304
print(fmt % (full_tag, tag_prefix))
305-
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
306-
full_tag,
307-
tag_prefix,
305+
pieces["error"] = "tag '{}' doesn't start with prefix '{}'".format(
306+
full_tag, tag_prefix
308307
)
309308
return pieces
310309
pieces["closest-tag"] = full_tag[len(tag_prefix) :]

xarray/backends/api.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -718,7 +718,7 @@ def open_mfdataset(
718718
autoclose=None,
719719
parallel=False,
720720
join="outer",
721-
**kwargs
721+
**kwargs,
722722
):
723723
"""Open multiple files as a single dataset.
724724
@@ -1258,9 +1258,7 @@ def _validate_append_dim_and_encoding(
12581258
return
12591259
if append_dim:
12601260
if append_dim not in ds.dims:
1261-
raise ValueError(
1262-
"{} not a valid dimension in the Dataset".format(append_dim)
1263-
)
1261+
raise ValueError(f"{append_dim} not a valid dimension in the Dataset")
12641262
for data_var in ds_to_append:
12651263
if data_var in ds:
12661264
if append_dim is None:

xarray/backends/file_manager.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def __init__(
8383
kwargs=None,
8484
lock=None,
8585
cache=None,
86-
ref_counts=None
86+
ref_counts=None,
8787
):
8888
"""Initialize a FileManager.
8989
@@ -267,7 +267,7 @@ def __setstate__(self, state):
267267
def __repr__(self):
268268
args_string = ", ".join(map(repr, self._args))
269269
if self._mode is not _DEFAULT_MODE:
270-
args_string += ", mode={!r}".format(self._mode)
270+
args_string += f", mode={self._mode!r}"
271271
return "{}({!r}, {}, kwargs={})".format(
272272
type(self).__name__, self._opener, args_string, self._kwargs
273273
)

xarray/backends/netCDF4_.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def _nc4_dtype(var):
137137
elif var.dtype.kind in ["i", "u", "f", "c", "S"]:
138138
dtype = var.dtype
139139
else:
140-
raise ValueError("unsupported dtype for netCDF4 variable: {}".format(var.dtype))
140+
raise ValueError(f"unsupported dtype for netCDF4 variable: {var.dtype}")
141141
return dtype
142142

143143

xarray/backends/netcdf3.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def coerce_nc3_dtype(arr):
5050
cast_arr = arr.astype(new_dtype)
5151
if not (cast_arr == arr).all():
5252
raise ValueError(
53-
"could not safely cast array from dtype %s to %s" % (dtype, new_dtype)
53+
f"could not safely cast array from dtype {dtype} to {new_dtype}"
5454
)
5555
arr = cast_arr
5656
return arr

xarray/backends/pydap_.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def _fix_attributes(attributes):
4949
# dot-separated key
5050
attributes.update(
5151
{
52-
"{}.{}".format(k, k_child): v_child
52+
f"{k}.{k_child}": v_child
5353
for k_child, v_child in attributes.pop(k).items()
5454
}
5555
)

xarray/coding/cftime_offsets.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -638,7 +638,7 @@ def __apply__(self, other):
638638

639639

640640
_FREQUENCY_CONDITION = "|".join(_FREQUENCIES.keys())
641-
_PATTERN = r"^((?P<multiple>\d+)|())(?P<freq>({}))$".format(_FREQUENCY_CONDITION)
641+
_PATTERN = fr"^((?P<multiple>\d+)|())(?P<freq>({_FREQUENCY_CONDITION}))$"
642642

643643

644644
# pandas defines these offsets as "Tick" objects, which for instance have
@@ -759,19 +759,15 @@ def _generate_range(start, end, periods, offset):
759759

760760
next_date = current + offset
761761
if next_date <= current:
762-
raise ValueError(
763-
"Offset {offset} did not increment date".format(offset=offset)
764-
)
762+
raise ValueError(f"Offset {offset} did not increment date")
765763
current = next_date
766764
else:
767765
while current >= end:
768766
yield current
769767

770768
next_date = current + offset
771769
if next_date >= current:
772-
raise ValueError(
773-
"Offset {offset} did not decrement date".format(offset=offset)
774-
)
770+
raise ValueError(f"Offset {offset} did not decrement date")
775771
current = next_date
776772

777773

xarray/coding/cftimeindex.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,7 @@ def shift(self, n, freq):
403403
from .cftime_offsets import to_offset
404404

405405
if not isinstance(n, int):
406-
raise TypeError("'n' must be an int, got {}.".format(n))
406+
raise TypeError(f"'n' must be an int, got {n}.")
407407
if isinstance(freq, timedelta):
408408
return self + n * freq
409409
elif isinstance(freq, str):

xarray/coding/strings.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ def shape(self):
228228
return self.array.shape[:-1]
229229

230230
def __repr__(self):
231-
return "%s(%r)" % (type(self).__name__, self.array)
231+
return "{}({!r})".format(type(self).__name__, self.array)
232232

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

xarray/coding/times.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ def infer_datetime_units(dates):
286286
# NumPy casting bug: https://github.com/numpy/numpy/issues/11096
287287
unique_timedeltas = to_timedelta_unboxed(unique_timedeltas)
288288
units = _infer_time_units_from_diff(unique_timedeltas)
289-
return "%s since %s" % (units, reference_date)
289+
return f"{units} since {reference_date}"
290290

291291

292292
def format_cftime_datetime(date):
@@ -341,7 +341,7 @@ def cftime_to_nptime(times):
341341
def _cleanup_netcdf_time_units(units):
342342
delta, ref_date = _unpack_netcdf_time_units(units)
343343
try:
344-
units = "%s since %s" % (delta, format_timestamp(ref_date))
344+
units = "{} since {}".format(delta, format_timestamp(ref_date))
345345
except OutOfBoundsDatetime:
346346
# don't worry about reifying the units if they're out of bounds
347347
pass

xarray/coding/variables.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,11 +73,8 @@ def __array__(self, dtype=None):
7373
return self.func(self.array)
7474

7575
def __repr__(self):
76-
return "%s(%r, func=%r, dtype=%r)" % (
77-
type(self).__name__,
78-
self.array,
79-
self.func,
80-
self.dtype,
76+
return "{}({!r}, func={!r}, dtype={!r})".format(
77+
type(self).__name__, self.array, self.func, self.dtype
8178
)
8279

8380

@@ -113,7 +110,7 @@ def unpack_for_decoding(var):
113110

114111
def safe_setitem(dest, key, value, name=None):
115112
if key in dest:
116-
var_str = " on variable {!r}".format(name) if name else ""
113+
var_str = f" on variable {name!r}" if name else ""
117114
raise ValueError(
118115
"failed to prevent overwriting existing key {} in attrs{}. "
119116
"This is probably an encoding field used by xarray to describe "

xarray/convert.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -229,16 +229,14 @@ def _iris_cell_methods_to_str(cell_methods_obj):
229229
"""
230230
cell_methods = []
231231
for cell_method in cell_methods_obj:
232-
names = "".join(["{}: ".format(n) for n in cell_method.coord_names])
232+
names = "".join([f"{n}: " for n in cell_method.coord_names])
233233
intervals = " ".join(
234-
["interval: {}".format(interval) for interval in cell_method.intervals]
235-
)
236-
comments = " ".join(
237-
["comment: {}".format(comment) for comment in cell_method.comments]
234+
[f"interval: {interval}" for interval in cell_method.intervals]
238235
)
236+
comments = " ".join([f"comment: {comment}" for comment in cell_method.comments])
239237
extra = " ".join([intervals, comments]).strip()
240238
if extra:
241-
extra = " ({})".format(extra)
239+
extra = f" ({extra})"
242240
cell_methods.append(names + cell_method.method + extra)
243241
return " ".join(cell_methods)
244242

@@ -267,11 +265,11 @@ def from_iris(cube):
267265
dim_coord = cube.coord(dim_coords=True, dimensions=(i,))
268266
dims.append(_name(dim_coord))
269267
except iris.exceptions.CoordinateNotFoundError:
270-
dims.append("dim_{}".format(i))
268+
dims.append(f"dim_{i}")
271269

272270
if len(set(dims)) != len(dims):
273271
duplicates = [k for k, v in Counter(dims).items() if v > 1]
274-
raise ValueError("Duplicate coordinate name {}.".format(duplicates))
272+
raise ValueError(f"Duplicate coordinate name {duplicates}.")
275273

276274
coords = {}
277275

xarray/core/alignment.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def align(
6464
copy=True,
6565
indexes=None,
6666
exclude=frozenset(),
67-
fill_value=dtypes.NA
67+
fill_value=dtypes.NA,
6868
):
6969
"""
7070
Given any number of Dataset and/or DataArray objects, returns new
@@ -294,9 +294,7 @@ def align(
294294
or dim in unlabeled_dim_sizes
295295
):
296296
if join == "exact":
297-
raise ValueError(
298-
"indexes along dimension {!r} are not equal".format(dim)
299-
)
297+
raise ValueError(f"indexes along dimension {dim!r} are not equal")
300298
index = joiner(matching_indexes)
301299
joined_indexes[dim] = index
302300
else:
@@ -402,7 +400,7 @@ def is_alignable(obj):
402400
copy=copy,
403401
indexes=indexes,
404402
exclude=exclude,
405-
fill_value=fill_value
403+
fill_value=fill_value,
406404
)
407405

408406
for position, key, aligned_obj in zip(positions, keys, aligned):

xarray/core/common.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def wrapped_func(self, dim=None, skipna=None, **kwargs):
8787
skipna=skipna,
8888
numeric_only=numeric_only,
8989
allow_lazy=True,
90-
**kwargs
90+
**kwargs,
9191
)
9292

9393
else:
@@ -167,7 +167,7 @@ def _get_axis_num(self: Any, dim: Hashable) -> int:
167167
try:
168168
return self.dims.index(dim)
169169
except ValueError:
170-
raise ValueError("%r not found in array dimensions %r" % (dim, self.dims))
170+
raise ValueError(f"{dim!r} not found in array dimensions {self.dims!r}")
171171

172172
@property
173173
def sizes(self: Any) -> Mapping[Hashable, int]:
@@ -225,7 +225,7 @@ def __getattr__(self, name: str) -> Any:
225225
with suppress(KeyError):
226226
return source[name]
227227
raise AttributeError(
228-
"%r object has no attribute %r" % (type(self).__name__, name)
228+
"{!r} object has no attribute {!r}".format(type(self).__name__, name)
229229
)
230230

231231
# This complicated two-method design boosts overall performance of simple operations
@@ -258,7 +258,9 @@ def __setattr__(self, name: str, value: Any) -> None:
258258
except AttributeError as e:
259259
# Don't accidentally shadow custom AttributeErrors, e.g.
260260
# DataArray.dims.setter
261-
if str(e) != "%r object has no attribute %r" % (type(self).__name__, name):
261+
if str(e) != "{!r} object has no attribute {!r}".format(
262+
type(self).__name__, name
263+
):
262264
raise
263265
raise AttributeError(
264266
"cannot set attribute %r on a %r object. Use __setitem__ style"
@@ -479,7 +481,7 @@ def pipe(
479481
self,
480482
func: Union[Callable[..., T], Tuple[Callable[..., T], str]],
481483
*args,
482-
**kwargs
484+
**kwargs,
483485
) -> T:
484486
"""
485487
Apply func(self, *args, **kwargs)
@@ -735,7 +737,7 @@ def rolling(
735737
dim: Mapping[Hashable, int] = None,
736738
min_periods: int = None,
737739
center: bool = False,
738-
**window_kwargs: int
740+
**window_kwargs: int,
739741
):
740742
"""
741743
Rolling window object.
@@ -799,7 +801,7 @@ def rolling_exp(
799801
self,
800802
window: Mapping[Hashable, int] = None,
801803
window_type: str = "span",
802-
**window_kwargs
804+
**window_kwargs,
803805
):
804806
"""
805807
Exponentially-weighted moving window.
@@ -840,7 +842,7 @@ def coarsen(
840842
boundary: str = "exact",
841843
side: Union[str, Mapping[Hashable, str]] = "left",
842844
coord_func: str = "mean",
843-
**window_kwargs: int
845+
**window_kwargs: int,
844846
):
845847
"""
846848
Coarsen object.
@@ -910,7 +912,7 @@ def resample(
910912
keep_attrs: bool = None,
911913
loffset=None,
912914
restore_coord_dims: bool = None,
913-
**indexer_kwargs: str
915+
**indexer_kwargs: str,
914916
):
915917
"""Returns a Resample object for performing resampling operations.
916918

0 commit comments

Comments
 (0)