Skip to content

Commit 8a9c471

Browse files
crusaderkymax-sixty
authored andcommitted
pyupgrade one-off run (#3190)
* pyupgrade (manually vetted and tweaked) * pyupgrade * Tweaks to Dataset.drop_dims() * mypy * More concise code
1 parent 04597a8 commit 8a9c471

33 files changed

+202
-156
lines changed

setup.cfg

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@ ignore_missing_imports = True
8383
ignore_missing_imports = True
8484
[mypy-seaborn.*]
8585
ignore_missing_imports = True
86+
[mypy-sparse.*]
87+
ignore_missing_imports = True
8688
[mypy-toolz.*]
8789
ignore_missing_imports = True
8890
[mypy-zarr.*]

versioneer.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
398398
stderr=(subprocess.PIPE if hide_stderr
399399
else None))
400400
break
401-
except EnvironmentError:
401+
except OSError:
402402
e = sys.exc_info()[1]
403403
if e.errno == errno.ENOENT:
404404
continue
@@ -421,7 +421,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
421421
return stdout, p.returncode
422422

423423

424-
LONG_VERSION_PY['git'] = '''
424+
LONG_VERSION_PY['git'] = r'''
425425
# This file helps to compute a version number in source trees obtained from
426426
# git-archive tarball (such as those provided by githubs download-from-tag
427427
# feature). Distribution tarballs (built by setup.py sdist) and build
@@ -968,7 +968,7 @@ def git_get_keywords(versionfile_abs):
968968
if mo:
969969
keywords["date"] = mo.group(1)
970970
f.close()
971-
except EnvironmentError:
971+
except OSError:
972972
pass
973973
return keywords
974974

@@ -992,11 +992,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
992992
if verbose:
993993
print("keywords are unexpanded, not using")
994994
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
995-
refs = set([r.strip() for r in refnames.strip("()").split(",")])
995+
refs = {r.strip() for r in refnames.strip("()").split(",")}
996996
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
997997
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
998998
TAG = "tag: "
999-
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
999+
tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
10001000
if not tags:
10011001
# Either we're using git < 1.8.3, or there really are no tags. We use
10021002
# a heuristic: assume all version tags have a digit. The old git %d
@@ -1005,7 +1005,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
10051005
# between branches and tags. By ignoring refnames without digits, we
10061006
# filter out many common branch names like "release" and
10071007
# "stabilization", as well as "HEAD" and "master".
1008-
tags = set([r for r in refs if re.search(r'\d', r)])
1008+
tags = {r for r in refs if re.search(r'\d', r)}
10091009
if verbose:
10101010
print("discarding '%s', no digits" % ",".join(refs - tags))
10111011
if verbose:
@@ -1148,7 +1148,7 @@ def do_vcs_install(manifest_in, versionfile_source, ipy):
11481148
if "export-subst" in line.strip().split()[1:]:
11491149
present = True
11501150
f.close()
1151-
except EnvironmentError:
1151+
except OSError:
11521152
pass
11531153
if not present:
11541154
f = open(".gitattributes", "a+")
@@ -1206,7 +1206,7 @@ def versions_from_file(filename):
12061206
try:
12071207
with open(filename) as f:
12081208
contents = f.read()
1209-
except EnvironmentError:
1209+
except OSError:
12101210
raise NotThisMethod("unable to read _version.py")
12111211
mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON",
12121212
contents, re.M | re.S)
@@ -1702,8 +1702,7 @@ def do_setup():
17021702
root = get_root()
17031703
try:
17041704
cfg = get_config_from_root(root)
1705-
except (EnvironmentError, configparser.NoSectionError,
1706-
configparser.NoOptionError) as e:
1705+
except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e:
17071706
if isinstance(e, (EnvironmentError, configparser.NoSectionError)):
17081707
print("Adding sample versioneer config to setup.cfg",
17091708
file=sys.stderr)
@@ -1728,7 +1727,7 @@ def do_setup():
17281727
try:
17291728
with open(ipy, "r") as f:
17301729
old = f.read()
1731-
except EnvironmentError:
1730+
except OSError:
17321731
old = ""
17331732
if INIT_PY_SNIPPET not in old:
17341733
print(" appending to %s" % ipy)
@@ -1752,7 +1751,7 @@ def do_setup():
17521751
if line.startswith("include "):
17531752
for include in line.split()[1:]:
17541753
simple_includes.add(include)
1755-
except EnvironmentError:
1754+
except OSError:
17561755
pass
17571756
# That doesn't cover everything MANIFEST.in can do
17581757
# (http://docs.python.org/2/distutils/sourcedist.html#commands), so

xarray/_version.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
8181
stderr=(subprocess.PIPE if hide_stderr
8282
else None))
8383
break
84-
except EnvironmentError:
84+
except OSError:
8585
e = sys.exc_info()[1]
8686
if e.errno == errno.ENOENT:
8787
continue
@@ -153,7 +153,7 @@ def git_get_keywords(versionfile_abs):
153153
if mo:
154154
keywords["date"] = mo.group(1)
155155
f.close()
156-
except EnvironmentError:
156+
except OSError:
157157
pass
158158
return keywords
159159

@@ -177,11 +177,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
177177
if verbose:
178178
print("keywords are unexpanded, not using")
179179
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
180-
refs = set([r.strip() for r in refnames.strip("()").split(",")])
180+
refs = {r.strip() for r in refnames.strip("()").split(",")}
181181
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
182182
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
183183
TAG = "tag: "
184-
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
184+
tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
185185
if not tags:
186186
# Either we're using git < 1.8.3, or there really are no tags. We use
187187
# a heuristic: assume all version tags have a digit. The old git %d
@@ -190,7 +190,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
190190
# between branches and tags. By ignoring refnames without digits, we
191191
# filter out many common branch names like "release" and
192192
# "stabilization", as well as "HEAD" and "master".
193-
tags = set([r for r in refs if re.search(r'\d', r)])
193+
tags = {r for r in refs if re.search(r'\d', r)}
194194
if verbose:
195195
print("discarding '%s', no digits" % ",".join(refs - tags))
196196
if verbose:

xarray/backends/api.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,7 @@ def open_mfdataset(paths, chunks=None, concat_dim='_not_supplied',
752752
paths = [str(p) if isinstance(p, Path) else p for p in paths]
753753

754754
if not paths:
755-
raise IOError('no files to open')
755+
raise OSError('no files to open')
756756

757757
# If combine='by_coords' then this is unnecessary, but quick.
758758
# If combine='nested' then this creates a flat list which is easier to
@@ -1051,7 +1051,7 @@ def save_mfdataset(datasets, paths, mode='w', format=None, groups=None,
10511051
if groups is None:
10521052
groups = [None] * len(datasets)
10531053

1054-
if len(set([len(datasets), len(paths), len(groups)])) > 1:
1054+
if len({len(datasets), len(paths), len(groups)}) > 1:
10551055
raise ValueError('must supply lists of the same length for the '
10561056
'datasets, paths and groups arguments to '
10571057
'save_mfdataset')

xarray/backends/netCDF4_.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ def _netcdf4_create_group(dataset, name):
138138

139139

140140
def _nc4_require_group(ds, group, mode, create_group=_netcdf4_create_group):
141-
if group in set([None, '', '/']):
141+
if group in {None, '', '/'}:
142142
# use the root group
143143
return ds
144144
else:
@@ -155,7 +155,7 @@ def _nc4_require_group(ds, group, mode, create_group=_netcdf4_create_group):
155155
ds = create_group(ds, key)
156156
else:
157157
# wrap error to provide slightly more helpful message
158-
raise IOError('group not found: %s' % key, e)
158+
raise OSError('group not found: %s' % key, e)
159159
return ds
160160

161161

@@ -195,9 +195,11 @@ def _extract_nc4_variable_encoding(variable, raise_on_invalid=False,
195195

196196
encoding = variable.encoding.copy()
197197

198-
safe_to_drop = set(['source', 'original_shape'])
199-
valid_encodings = set(['zlib', 'complevel', 'fletcher32', 'contiguous',
200-
'chunksizes', 'shuffle', '_FillValue', 'dtype'])
198+
safe_to_drop = {'source', 'original_shape'}
199+
valid_encodings = {
200+
'zlib', 'complevel', 'fletcher32', 'contiguous',
201+
'chunksizes', 'shuffle', '_FillValue', 'dtype'
202+
}
201203
if lsd_okay:
202204
valid_encodings.add('least_significant_digit')
203205
if h5py_okay:

xarray/backends/netcdf3.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@
1111

1212
# The following are reserved names in CDL and may not be used as names of
1313
# variables, dimension, attributes
14-
_reserved_names = set(['byte', 'char', 'short', 'ushort', 'int', 'uint',
15-
'int64', 'uint64', 'float' 'real', 'double', 'bool',
16-
'string'])
14+
_reserved_names = {
15+
'byte', 'char', 'short', 'ushort', 'int', 'uint', 'int64', 'uint64',
16+
'float' 'real', 'double', 'bool', 'string'
17+
}
1718

1819
# These data-types aren't supported by netCDF3, so they are automatically
1920
# coerced instead as indicated by the "coerce_nc3_dtype" function
@@ -108,4 +109,4 @@ def is_valid_nc3_name(s):
108109
('/' not in s) and
109110
(s[-1] != ' ') and
110111
(_isalnumMUTF8(s[0]) or (s[0] == '_')) and
111-
all((_isalnumMUTF8(c) or c in _specialchars for c in s)))
112+
all(_isalnumMUTF8(c) or c in _specialchars for c in s))

xarray/backends/pseudonetcdf_.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,18 +75,18 @@ def get_variables(self):
7575
for k, v in self.ds.variables.items())
7676

7777
def get_attrs(self):
78-
return Frozen(dict([(k, getattr(self.ds, k))
79-
for k in self.ds.ncattrs()]))
78+
return Frozen({k: getattr(self.ds, k) for k in self.ds.ncattrs()})
8079

8180
def get_dimensions(self):
8281
return Frozen(self.ds.dimensions)
8382

8483
def get_encoding(self):
85-
encoding = {}
86-
encoding['unlimited_dims'] = set(
87-
[k for k in self.ds.dimensions
88-
if self.ds.dimensions[k].isunlimited()])
89-
return encoding
84+
return {
85+
'unlimited_dims': {
86+
k for k in self.ds.dimensions
87+
if self.ds.dimensions[k].isunlimited()
88+
}
89+
}
9090

9191
def close(self):
9292
self._manager.close()

xarray/backends/pynio_.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,12 @@ def get_dimensions(self):
7575
return Frozen(self.ds.dimensions)
7676

7777
def get_encoding(self):
78-
encoding = {}
79-
encoding['unlimited_dims'] = set(
80-
[k for k in self.ds.dimensions if self.ds.unlimited(k)])
81-
return encoding
78+
return {
79+
'unlimited_dims': {
80+
k for k in self.ds.dimensions
81+
if self.ds.unlimited(k)
82+
}
83+
}
8284

8385
def close(self):
8486
self._manager.close()

xarray/backends/zarr.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -166,8 +166,7 @@ def _get_zarr_dims_and_attrs(zarr_obj, dimension_key):
166166
def _extract_zarr_variable_encoding(variable, raise_on_invalid=False):
167167
encoding = variable.encoding.copy()
168168

169-
valid_encodings = set(['chunks', 'compressor', 'filters',
170-
'cache_metadata'])
169+
valid_encodings = {'chunks', 'compressor', 'filters', 'cache_metadata'}
171170

172171
if raise_on_invalid:
173172
invalid = [k for k in encoding if k not in valid_encodings]
@@ -340,8 +339,10 @@ def store(self, variables, attributes, check_encoding_set=frozenset(),
340339
only needed in append mode
341340
"""
342341

343-
existing_variables = set([vn for vn in variables
344-
if _encode_variable_name(vn) in self.ds])
342+
existing_variables = {
343+
vn for vn in variables
344+
if _encode_variable_name(vn) in self.ds
345+
}
345346
new_variables = set(variables) - existing_variables
346347
variables_without_encoding = OrderedDict([(vn, variables[vn])
347348
for vn in new_variables])

xarray/coding/cftime_offsets.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -637,7 +637,7 @@ def __apply__(self, other):
637637

638638

639639
_FREQUENCY_CONDITION = '|'.join(_FREQUENCIES.keys())
640-
_PATTERN = r'^((?P<multiple>\d+)|())(?P<freq>({0}))$'.format(
640+
_PATTERN = r'^((?P<multiple>\d+)|())(?P<freq>({}))$'.format(
641641
_FREQUENCY_CONDITION)
642642

643643

xarray/coding/times.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424

2525
# standard calendars recognized by cftime
26-
_STANDARD_CALENDARS = set(['standard', 'gregorian', 'proleptic_gregorian'])
26+
_STANDARD_CALENDARS = {'standard', 'gregorian', 'proleptic_gregorian'}
2727

2828
_NS_PER_TIME_DELTA = {'us': int(1e3),
2929
'ms': int(1e6),

xarray/conventions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ def ensure_dtype_not_object(var, name=None):
186186
if strings.is_bytes_dtype(inferred_dtype):
187187
fill_value = b''
188188
elif strings.is_unicode_dtype(inferred_dtype):
189-
fill_value = u''
189+
fill_value = ''
190190
else:
191191
# insist on using float for numeric values
192192
if not np.issubdtype(inferred_dtype, np.floating):

xarray/convert.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def encode(var):
3030
def _filter_attrs(attrs, ignored_attrs):
3131
""" Return attrs that are not in ignored_attrs
3232
"""
33-
return dict((k, v) for k, v in attrs.items() if k not in ignored_attrs)
33+
return {k: v for k, v in attrs.items() if k not in ignored_attrs}
3434

3535

3636
def from_cdms2(variable):
@@ -119,7 +119,7 @@ def set_cdms2_attrs(var, attrs):
119119
def _pick_attrs(attrs, keys):
120120
""" Return attrs with keys in keys list
121121
"""
122-
return dict((k, v) for k, v in attrs.items() if k in keys)
122+
return {k: v for k, v in attrs.items() if k in keys}
123123

124124

125125
def _get_iris_args(attrs):
@@ -188,7 +188,7 @@ def _iris_obj_to_attrs(obj):
188188
if obj.units.origin != '1' and not obj.units.is_unknown():
189189
attrs['units'] = obj.units.origin
190190
attrs.update(obj.attributes)
191-
return dict((k, v) for k, v in attrs.items() if v is not None)
191+
return {k: v for k, v in attrs.items() if v is not None}
192192

193193

194194
def _iris_cell_methods_to_str(cell_methods_obj):

xarray/core/alignment.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -341,10 +341,10 @@ def reindex_variables(
341341
for dim, indexer in indexers.items():
342342
if isinstance(indexer, DataArray) and indexer.dims != (dim,):
343343
warnings.warn(
344-
"Indexer has dimensions {0:s} that are different "
345-
"from that to be indexed along {1:s}. "
346-
"This will behave differently in the future.".format(
347-
str(indexer.dims), dim),
344+
"Indexer has dimensions {:s} that are different "
345+
"from that to be indexed along {:s}. "
346+
"This will behave differently in the future."
347+
.format(str(indexer.dims), dim),
348348
FutureWarning, stacklevel=3)
349349

350350
target = new_indexes[dim] = utils.safe_cast_to_index(indexers[dim])

xarray/core/combine.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,8 @@ def _infer_tile_ids_from_nested_list(entry, current_pos):
4141

4242
if isinstance(entry, list):
4343
for i, item in enumerate(entry):
44-
for result in _infer_tile_ids_from_nested_list(item,
45-
current_pos + (i,)):
46-
yield result
44+
yield from _infer_tile_ids_from_nested_list(
45+
item, current_pos + (i,))
4746
else:
4847
yield current_pos, entry
4948

@@ -735,10 +734,12 @@ def _auto_concat(datasets, dim=None, data_vars='all', coords='different',
735734
concat_dims = set(ds0.dims)
736735
if ds0.dims != ds1.dims:
737736
dim_tuples = set(ds0.dims.items()) - set(ds1.dims.items())
738-
concat_dims = set(i for i, _ in dim_tuples)
737+
concat_dims = {i for i, _ in dim_tuples}
739738
if len(concat_dims) > 1:
740-
concat_dims = set(d for d in concat_dims
741-
if not ds0[d].equals(ds1[d]))
739+
concat_dims = {
740+
d for d in concat_dims
741+
if not ds0[d].equals(ds1[d])
742+
}
742743
if len(concat_dims) > 1:
743744
raise ValueError('too many different dimensions to '
744745
'concatenate: %s' % concat_dims)

xarray/core/dataarray.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1389,7 +1389,7 @@ def expand_dims(self, dim: Union[None, Hashable, Sequence[Hashable],
13891389
elif isinstance(dim, Sequence) and not isinstance(dim, str):
13901390
if len(dim) != len(set(dim)):
13911391
raise ValueError('dims should not contain duplicate values.')
1392-
dim = OrderedDict(((d, 1) for d in dim))
1392+
dim = OrderedDict((d, 1) for d in dim)
13931393
elif dim is not None and not isinstance(dim, Mapping):
13941394
dim = OrderedDict(((cast(Hashable, dim), 1),))
13951395

0 commit comments

Comments
 (0)