Skip to content

Commit

Permalink
Python3.6 idioms (#3419)
Browse files Browse the repository at this point in the history
* pyupgrade --py36-plus

* Update xarray/core/nputils.py

Co-Authored-By: crusaderky <crusaderky@gmail.com>

* Update xarray/core/parallel.py

Co-Authored-By: crusaderky <crusaderky@gmail.com>

* Update xarray/tests/test_cftime_offsets.py

Co-Authored-By: crusaderky <crusaderky@gmail.com>

* Update xarray/tests/test_cftime_offsets.py

Co-Authored-By: crusaderky <crusaderky@gmail.com>
  • Loading branch information
max-sixty and crusaderky committed Oct 21, 2019
1 parent 9886e3c commit 3c462b9
Show file tree
Hide file tree
Showing 57 changed files with 200 additions and 221 deletions.
1 change: 0 additions & 1 deletion doc/gallery/plot_cartopy_facetgrid.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
==================================
Multiple plots and map projections
Expand Down
1 change: 0 additions & 1 deletion doc/gallery/plot_colorbar_center.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
==================
Centered colormaps
Expand Down
1 change: 0 additions & 1 deletion doc/gallery/plot_control_colorbar.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
===========================
Control the plot's colorbar
Expand Down
1 change: 0 additions & 1 deletion doc/gallery/plot_lines_from_2d.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
==================================
Multiple lines from a 2d DataArray
Expand Down
1 change: 0 additions & 1 deletion doc/gallery/plot_rasterio.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
.. _recipes.rasterio:
Expand Down
1 change: 0 additions & 1 deletion doc/gallery/plot_rasterio_rgb.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
.. _recipes.rasterio_rgb:
Expand Down
7 changes: 3 additions & 4 deletions xarray/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
print(f"unable to find command, tried {commands}")
return None, None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
Expand Down Expand Up @@ -302,9 +302,8 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
full_tag,
tag_prefix,
pieces["error"] = "tag '{}' doesn't start with prefix '{}'".format(
full_tag, tag_prefix
)
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix) :]
Expand Down
6 changes: 2 additions & 4 deletions xarray/backends/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,7 @@ def open_mfdataset(
autoclose=None,
parallel=False,
join="outer",
**kwargs
**kwargs,
):
"""Open multiple files as a single dataset.
Expand Down Expand Up @@ -1258,9 +1258,7 @@ def _validate_append_dim_and_encoding(
return
if append_dim:
if append_dim not in ds.dims:
raise ValueError(
"{} not a valid dimension in the Dataset".format(append_dim)
)
raise ValueError(f"{append_dim} not a valid dimension in the Dataset")
for data_var in ds_to_append:
if data_var in ds:
if append_dim is None:
Expand Down
4 changes: 2 additions & 2 deletions xarray/backends/file_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def __init__(
kwargs=None,
lock=None,
cache=None,
ref_counts=None
ref_counts=None,
):
"""Initialize a FileManager.
Expand Down Expand Up @@ -267,7 +267,7 @@ def __setstate__(self, state):
def __repr__(self):
args_string = ", ".join(map(repr, self._args))
if self._mode is not _DEFAULT_MODE:
args_string += ", mode={!r}".format(self._mode)
args_string += f", mode={self._mode!r}"
return "{}({!r}, {}, kwargs={})".format(
type(self).__name__, self._opener, args_string, self._kwargs
)
Expand Down
2 changes: 1 addition & 1 deletion xarray/backends/netCDF4_.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def _nc4_dtype(var):
elif var.dtype.kind in ["i", "u", "f", "c", "S"]:
dtype = var.dtype
else:
raise ValueError("unsupported dtype for netCDF4 variable: {}".format(var.dtype))
raise ValueError(f"unsupported dtype for netCDF4 variable: {var.dtype}")
return dtype


Expand Down
2 changes: 1 addition & 1 deletion xarray/backends/netcdf3.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def coerce_nc3_dtype(arr):
cast_arr = arr.astype(new_dtype)
if not (cast_arr == arr).all():
raise ValueError(
"could not safely cast array from dtype %s to %s" % (dtype, new_dtype)
f"could not safely cast array from dtype {dtype} to {new_dtype}"
)
arr = cast_arr
return arr
Expand Down
2 changes: 1 addition & 1 deletion xarray/backends/pydap_.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def _fix_attributes(attributes):
# dot-separated key
attributes.update(
{
"{}.{}".format(k, k_child): v_child
f"{k}.{k_child}": v_child
for k_child, v_child in attributes.pop(k).items()
}
)
Expand Down
10 changes: 3 additions & 7 deletions xarray/coding/cftime_offsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ def __apply__(self, other):


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


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

next_date = current + offset
if next_date <= current:
raise ValueError(
"Offset {offset} did not increment date".format(offset=offset)
)
raise ValueError(f"Offset {offset} did not increment date")
current = next_date
else:
while current >= end:
yield current

next_date = current + offset
if next_date >= current:
raise ValueError(
"Offset {offset} did not decrement date".format(offset=offset)
)
raise ValueError(f"Offset {offset} did not decrement date")
current = next_date


Expand Down
2 changes: 1 addition & 1 deletion xarray/coding/cftimeindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ def shift(self, n, freq):
from .cftime_offsets import to_offset

if not isinstance(n, int):
raise TypeError("'n' must be an int, got {}.".format(n))
raise TypeError(f"'n' must be an int, got {n}.")
if isinstance(freq, timedelta):
return self + n * freq
elif isinstance(freq, str):
Expand Down
2 changes: 1 addition & 1 deletion xarray/coding/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def shape(self):
return self.array.shape[:-1]

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

def __getitem__(self, key):
# require slicing the last dimension completely
Expand Down
4 changes: 2 additions & 2 deletions xarray/coding/times.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def infer_datetime_units(dates):
# NumPy casting bug: https://github.com/numpy/numpy/issues/11096
unique_timedeltas = to_timedelta_unboxed(unique_timedeltas)
units = _infer_time_units_from_diff(unique_timedeltas)
return "%s since %s" % (units, reference_date)
return f"{units} since {reference_date}"


def format_cftime_datetime(date):
Expand Down Expand Up @@ -341,7 +341,7 @@ def cftime_to_nptime(times):
def _cleanup_netcdf_time_units(units):
delta, ref_date = _unpack_netcdf_time_units(units)
try:
units = "%s since %s" % (delta, format_timestamp(ref_date))
units = "{} since {}".format(delta, format_timestamp(ref_date))
except OutOfBoundsDatetime:
# don't worry about reifying the units if they're out of bounds
pass
Expand Down
9 changes: 3 additions & 6 deletions xarray/coding/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,8 @@ def __array__(self, dtype=None):
return self.func(self.array)

def __repr__(self):
return "%s(%r, func=%r, dtype=%r)" % (
type(self).__name__,
self.array,
self.func,
self.dtype,
return "{}({!r}, func={!r}, dtype={!r})".format(
type(self).__name__, self.array, self.func, self.dtype
)


Expand Down Expand Up @@ -113,7 +110,7 @@ def unpack_for_decoding(var):

def safe_setitem(dest, key, value, name=None):
if key in dest:
var_str = " on variable {!r}".format(name) if name else ""
var_str = f" on variable {name!r}" if name else ""
raise ValueError(
"failed to prevent overwriting existing key {} in attrs{}. "
"This is probably an encoding field used by xarray to describe "
Expand Down
14 changes: 6 additions & 8 deletions xarray/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,16 +229,14 @@ def _iris_cell_methods_to_str(cell_methods_obj):
"""
cell_methods = []
for cell_method in cell_methods_obj:
names = "".join(["{}: ".format(n) for n in cell_method.coord_names])
names = "".join([f"{n}: " for n in cell_method.coord_names])
intervals = " ".join(
["interval: {}".format(interval) for interval in cell_method.intervals]
)
comments = " ".join(
["comment: {}".format(comment) for comment in cell_method.comments]
[f"interval: {interval}" for interval in cell_method.intervals]
)
comments = " ".join([f"comment: {comment}" for comment in cell_method.comments])
extra = " ".join([intervals, comments]).strip()
if extra:
extra = " ({})".format(extra)
extra = f" ({extra})"
cell_methods.append(names + cell_method.method + extra)
return " ".join(cell_methods)

Expand Down Expand Up @@ -267,11 +265,11 @@ def from_iris(cube):
dim_coord = cube.coord(dim_coords=True, dimensions=(i,))
dims.append(_name(dim_coord))
except iris.exceptions.CoordinateNotFoundError:
dims.append("dim_{}".format(i))
dims.append(f"dim_{i}")

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

coords = {}

Expand Down
8 changes: 3 additions & 5 deletions xarray/core/alignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def align(
copy=True,
indexes=None,
exclude=frozenset(),
fill_value=dtypes.NA
fill_value=dtypes.NA,
):
"""
Given any number of Dataset and/or DataArray objects, returns new
Expand Down Expand Up @@ -294,9 +294,7 @@ def align(
or dim in unlabeled_dim_sizes
):
if join == "exact":
raise ValueError(
"indexes along dimension {!r} are not equal".format(dim)
)
raise ValueError(f"indexes along dimension {dim!r} are not equal")
index = joiner(matching_indexes)
joined_indexes[dim] = index
else:
Expand Down Expand Up @@ -402,7 +400,7 @@ def is_alignable(obj):
copy=copy,
indexes=indexes,
exclude=exclude,
fill_value=fill_value
fill_value=fill_value,
)

for position, key, aligned_obj in zip(positions, keys, aligned):
Expand Down
20 changes: 11 additions & 9 deletions xarray/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def wrapped_func(self, dim=None, skipna=None, **kwargs):
skipna=skipna,
numeric_only=numeric_only,
allow_lazy=True,
**kwargs
**kwargs,
)

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

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

# This complicated two-method design boosts overall performance of simple operations
Expand Down Expand Up @@ -258,7 +258,9 @@ def __setattr__(self, name: str, value: Any) -> None:
except AttributeError as e:
# Don't accidentally shadow custom AttributeErrors, e.g.
# DataArray.dims.setter
if str(e) != "%r object has no attribute %r" % (type(self).__name__, name):
if str(e) != "{!r} object has no attribute {!r}".format(
type(self).__name__, name
):
raise
raise AttributeError(
"cannot set attribute %r on a %r object. Use __setitem__ style"
Expand Down Expand Up @@ -479,7 +481,7 @@ def pipe(
self,
func: Union[Callable[..., T], Tuple[Callable[..., T], str]],
*args,
**kwargs
**kwargs,
) -> T:
"""
Apply func(self, *args, **kwargs)
Expand Down Expand Up @@ -735,7 +737,7 @@ def rolling(
dim: Mapping[Hashable, int] = None,
min_periods: int = None,
center: bool = False,
**window_kwargs: int
**window_kwargs: int,
):
"""
Rolling window object.
Expand Down Expand Up @@ -799,7 +801,7 @@ def rolling_exp(
self,
window: Mapping[Hashable, int] = None,
window_type: str = "span",
**window_kwargs
**window_kwargs,
):
"""
Exponentially-weighted moving window.
Expand Down Expand Up @@ -840,7 +842,7 @@ def coarsen(
boundary: str = "exact",
side: Union[str, Mapping[Hashable, str]] = "left",
coord_func: str = "mean",
**window_kwargs: int
**window_kwargs: int,
):
"""
Coarsen object.
Expand Down Expand Up @@ -910,7 +912,7 @@ def resample(
keep_attrs: bool = None,
loffset=None,
restore_coord_dims: bool = None,
**indexer_kwargs: str
**indexer_kwargs: str,
):
"""Returns a Resample object for performing resampling operations.
Expand Down
Loading

0 comments on commit 3c462b9

Please sign in to comment.