From 7730df234489fa41aab8294b3795fc018fe88f6e Mon Sep 17 00:00:00 2001 From: Matt Roeschke Date: Mon, 20 Nov 2017 00:10:00 -0800 Subject: [PATCH 1/4] CLN: Replace comprehensions list/set/dict functions with corresponding symbols --- asv_bench/benchmarks/frame_ctor.py | 6 ++--- asv_bench/benchmarks/packers.py | 2 +- asv_bench/benchmarks/replace.py | 6 ++--- ci/lint.sh | 13 ++++++++++ doc/sphinxext/numpydoc/phantom_import.py | 4 ++-- pandas/_libs/tslibs/offsets.pyx | 2 +- pandas/_libs/tslibs/resolution.pyx | 2 +- pandas/_version.py | 6 ++--- pandas/core/common.py | 2 +- pandas/core/dtypes/concat.py | 4 ++-- pandas/core/frame.py | 15 ++++++------ pandas/core/generic.py | 24 +++++++++---------- pandas/core/groupby.py | 2 +- pandas/core/indexes/base.py | 4 ++-- pandas/core/indexes/interval.py | 2 +- pandas/core/internals.py | 6 ++--- pandas/core/ops.py | 2 +- pandas/core/panelnd.py | 2 +- pandas/core/reshape/concat.py | 2 +- pandas/core/reshape/melt.py | 2 +- pandas/core/sparse/frame.py | 9 ++++--- pandas/io/clipboards.py | 2 +- pandas/io/json/json.py | 16 +++++-------- pandas/io/parsers.py | 14 +++++------ pandas/io/pytables.py | 11 ++++----- pandas/io/sql.py | 2 +- pandas/plotting/_converter.py | 2 +- pandas/tests/frame/common.py | 11 ++++----- pandas/tests/frame/test_api.py | 2 +- pandas/tests/frame/test_constructors.py | 25 ++++++++++---------- pandas/tests/groupby/test_groupby.py | 2 +- pandas/tests/groupby/test_whitelist.py | 2 +- pandas/tests/indexes/test_multi.py | 4 ++-- pandas/tests/indexing/test_panel.py | 2 +- pandas/tests/io/formats/test_format.py | 14 +++++------ pandas/tests/io/formats/test_to_latex.py | 20 ++++++++-------- pandas/tests/io/json/test_ujson.py | 2 +- pandas/tests/io/msgpack/test_case.py | 4 ++-- pandas/tests/io/msgpack/test_pack.py | 2 +- pandas/tests/io/test_packers.py | 8 +++---- pandas/tests/io/test_pytables.py | 2 +- pandas/tests/io/test_stata.py | 4 ++-- pandas/tests/plotting/test_series.py | 2 +- pandas/tests/reshape/test_join.py | 2 +- pandas/tests/series/test_constructors.py | 2 +- pandas/tests/series/test_indexing.py | 2 +- pandas/tests/test_panel.py | 30 ++++++++++++------------ pandas/tests/test_panel4d.py | 2 +- pandas/tseries/holiday.py | 4 ++-- pandas/tseries/offsets.py | 8 +++---- pandas/util/testing.py | 10 ++++---- 51 files changed, 166 insertions(+), 164 deletions(-) diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py index 7f95e8d06eb72..2ee5f5da7a84a 100644 --- a/asv_bench/benchmarks/frame_ctor.py +++ b/asv_bench/benchmarks/frame_ctor.py @@ -23,9 +23,9 @@ def setup(self): self.some_dict = list(self.data.values())[0] self.dict_list = [dict(zip(self.columns, row)) for row in self.frame.values] - self.data2 = dict( - ((i, dict(((j, float(j)) for j in range(100)))) for i in - range(2000))) + self.data2 = {i: {j: float(j) for j in range(100)} + for i in range(2000)} + def time_frame_ctor_list_of_dict(self): DataFrame(self.dict_list) diff --git a/asv_bench/benchmarks/packers.py b/asv_bench/benchmarks/packers.py index 927f1505e85c6..758162f000e8d 100644 --- a/asv_bench/benchmarks/packers.py +++ b/asv_bench/benchmarks/packers.py @@ -18,7 +18,7 @@ def _setup(self): self.N = 100000 self.C = 5 self.index = date_range('20000101', periods=self.N, freq='H') - self.df = DataFrame(dict(('float{0}'.format(i), randn(self.N)) for i in range(self.C)), index=self.index) + self.df = DataFrame({'float{0}'.format(i): randn(self.N) for i in range(self.C)}, index=self.index) self.df2 = self.df.copy() self.df2['object'] = [('%08x' % randrange((16 ** 8))) for _ in range(self.N)] self.remove(self.f) diff --git a/asv_bench/benchmarks/replace.py b/asv_bench/benchmarks/replace.py index 63562f90eab2b..157d5fe1e3948 100644 --- a/asv_bench/benchmarks/replace.py +++ b/asv_bench/benchmarks/replace.py @@ -23,7 +23,7 @@ class replace_large_dict(object): def setup(self): self.n = (10 ** 6) self.start_value = (10 ** 5) - self.to_rep = dict(((i, (self.start_value + i)) for i in range(self.n))) + self.to_rep = {i: self.start_value + i for i in range(self.n)} self.s = Series(np.random.randint(self.n, size=(10 ** 3))) def time_replace_large_dict(self): @@ -35,8 +35,8 @@ class replace_convert(object): def setup(self): self.n = (10 ** 3) - self.to_ts = dict(((i, pd.Timestamp(i)) for i in range(self.n))) - self.to_td = dict(((i, pd.Timedelta(i)) for i in range(self.n))) + self.to_ts = {i: pd.Timestamp(i) for i in range(self.n)} + self.to_td = {i: pd.Timedelta(i) for i in range(self.n)} self.s = Series(np.random.randint(self.n, size=(10 ** 3))) self.df = DataFrame({'A': np.random.randint(self.n, size=(10 ** 3)), 'B': np.random.randint(self.n, size=(10 ** 3))}) diff --git a/ci/lint.sh b/ci/lint.sh index 4027737900bf9..c1722e2b99e3e 100755 --- a/ci/lint.sh +++ b/ci/lint.sh @@ -97,6 +97,19 @@ if [ "$LINT" ]; then fi echo "Check for use of lists instead of generators in built-in Python functions DONE" + echo "Check for use of comprehensions using set(), dict() or list()" + + # Example: Avoid `list(i for i in some_iterator)` in favor of `[i for i in some_iterator]` + # + # Check the following functions: + # list(), set(), dict() + grep -R --include="*.py*" -E "(list|dict|[^frozen]set)\([^\{)=]* for .* in [^}]*\)" + + if [ $? = "0" ]; then + RET=1 + fi + echo "Check for use of comprehensions using set(), dict() or list() DONE" + else echo "NOT Linting" fi diff --git a/doc/sphinxext/numpydoc/phantom_import.py b/doc/sphinxext/numpydoc/phantom_import.py index e0bd645f5db76..f33dd838e8bb3 100755 --- a/doc/sphinxext/numpydoc/phantom_import.py +++ b/doc/sphinxext/numpydoc/phantom_import.py @@ -60,8 +60,8 @@ def import_phantom_module(xml_file): # Sort items so that # - Base classes come before classes inherited from them # - Modules come before their contents - all_nodes = dict((n.attrib['id'], n) for n in root) - + all_nodes = {n.attrib['id']: n for n in root} + def _get_bases(node, recurse=False): bases = [x.attrib['ref'] for x in node.findall('base')] if recurse: diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 526595e3a2eda..b03d48bba1649 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -33,7 +33,7 @@ from np_datetime cimport (pandas_datetimestruct, _MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] _int_to_month = {(k + 1): v for k, v in enumerate(_MONTHS)} -_month_to_int = dict((v, k) for k, v in _int_to_month.items()) +_month_to_int = {v: k for k, v in _int_to_month.items()} class WeekDay(object): diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index 388075903a8ba..0692d985b4877 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -53,7 +53,7 @@ _ONE_HOUR = 60 * _ONE_MINUTE _ONE_DAY = 24 * _ONE_HOUR DAYS = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'] -_weekday_rule_aliases = dict((k, v) for k, v in enumerate(DAYS)) +_weekday_rule_aliases = {k: v for k, v in enumerate(DAYS)} _MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] diff --git a/pandas/_version.py b/pandas/_version.py index 4a469ebb8630e..624c7b5cd63a1 100644 --- a/pandas/_version.py +++ b/pandas/_version.py @@ -141,11 +141,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set(r.strip() for r in refnames.strip("()").split(",")) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -154,7 +154,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set(r for r in refs if re.search(r'\d', r)) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '{}', no digits".format(",".join(refs - tags))) if verbose: diff --git a/pandas/core/common.py b/pandas/core/common.py index 8e12ce3647340..76a69030463ec 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -347,7 +347,7 @@ def map_indices_py(arr): Returns a dictionary with (element, index) pairs for each element in the given array/list """ - return dict((x, i) for i, x in enumerate(arr)) + return {x: i for i, x in enumerate(arr)} def union(*seqs): diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 7f9245bb31530..c1ba018adbcec 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -459,7 +459,7 @@ def _concat_datetimetz(to_concat, name=None): it is used in DatetimeIndex.append also """ # do not pass tz to set because tzlocal cannot be hashed - if len(set(str(x.dtype) for x in to_concat)) != 1: + if len({str(x.dtype) for x in to_concat}) != 1: raise ValueError('to_concat must have the same tz') tz = to_concat[0].tz # no need to localize because internal repr will not be changed @@ -525,7 +525,7 @@ def convert_sparse(x, axis): if len(typs) == 1: # concat input as it is if all inputs are sparse # and have the same fill_value - fill_values = set(c.fill_value for c in to_concat) + fill_values = {c.fill_value for c in to_concat} if len(fill_values) == 1: sp_values = [c.sp_values for c in to_concat] indexes = [c.sp_index.to_int_index() for c in to_concat] diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b05cfe41fd9d1..ae1bbd89df9b2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -347,7 +347,7 @@ def __init__(self, data=None, index=None, columns=None, dtype=None, elif isinstance(data, (np.ndarray, Series, Index)): if data.dtype.names: data_columns = list(data.dtype.names) - data = dict((k, data[k]) for k in data_columns) + data = {k: data[k] for k in data_columns} if columns is None: columns = data_columns mgr = self._init_dict(data, index, columns, dtype=dtype) @@ -417,8 +417,7 @@ def _init_dict(self, data, index, columns, dtype=None): extract_index(list(data.values())) # prefilter if columns passed - data = dict((k, v) for k, v in compat.iteritems(data) - if k in columns) + data = {k: v for k, v in compat.iteritems(data) if k in columns} if index is None: index = extract_index(list(data.values())) @@ -3895,7 +3894,7 @@ def f(col): return self._constructor_sliced(r, index=new_index, dtype=r.dtype) - result = dict((col, f(col)) for col in this) + result = {col: f(col) for col in this} # non-unique else: @@ -3906,7 +3905,7 @@ def f(i): return self._constructor_sliced(r, index=new_index, dtype=r.dtype) - result = dict((i, f(i)) for i, col in enumerate(this.columns)) + result = {i: f(i) for i, col in enumerate(this.columns)} result = self._constructor(result, index=new_index, copy=False) result.columns = new_columns return result @@ -3984,7 +3983,7 @@ def _compare_frame_evaluate(self, other, func, str_rep, try_cast=True): if self.columns.is_unique: def _compare(a, b): - return dict((col, func(a[col], b[col])) for col in a.columns) + return {col: func(a[col], b[col]) for col in a.columns} new_data = expressions.evaluate(_compare, str_rep, self, other) return self._constructor(data=new_data, index=self.index, @@ -3993,8 +3992,8 @@ def _compare(a, b): else: def _compare(a, b): - return dict((i, func(a.iloc[:, i], b.iloc[:, i])) - for i, col in enumerate(a.columns)) + return {i: func(a.iloc[:, i], b.iloc[:, i]) + for i, col in enumerate(a.columns)} new_data = expressions.evaluate(_compare, str_rep, self, other) result = self._constructor(data=new_data, index=self.index, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 782971a742b54..548f228cdd96b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -235,10 +235,10 @@ def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None, """ cls._AXIS_ORDERS = axes - cls._AXIS_NUMBERS = dict((a, i) for i, a in enumerate(axes)) + cls._AXIS_NUMBERS = {a: i for i, a in enumerate(axes)} cls._AXIS_LEN = len(axes) cls._AXIS_ALIASES = aliases or dict() - cls._AXIS_IALIASES = dict((v, k) for k, v in cls._AXIS_ALIASES.items()) + cls._AXIS_IALIASES = {v: k for k, v in cls._AXIS_ALIASES.items()} cls._AXIS_NAMES = dict(enumerate(axes)) cls._AXIS_SLICEMAP = slicers or None cls._AXIS_REVERSED = axes_are_reversed @@ -279,21 +279,21 @@ def set_axis(a, i): def _construct_axes_dict(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" - d = dict((a, self._get_axis(a)) for a in (axes or self._AXIS_ORDERS)) + d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)} d.update(kwargs) return d @staticmethod def _construct_axes_dict_from(self, axes, **kwargs): """Return an axes dictionary for the passed axes.""" - d = dict((a, ax) for a, ax in zip(self._AXIS_ORDERS, axes)) + d = {a: ax for a, ax in zip(self._AXIS_ORDERS, axes)} d.update(kwargs) return d def _construct_axes_dict_for_slice(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" - d = dict((self._AXIS_SLICEMAP[a], self._get_axis(a)) - for a in (axes or self._AXIS_ORDERS)) + d = {self._AXIS_SLICEMAP[a]: self._get_axis(a) + for a in (axes or self._AXIS_ORDERS)} d.update(kwargs) return d @@ -329,7 +329,7 @@ def _construct_axes_from_arguments(self, args, kwargs, require_all=False): raise TypeError("not enough/duplicate arguments " "specified!") - axes = dict((a, kwargs.pop(a, None)) for a in self._AXIS_ORDERS) + axes = {a: kwargs.pop(a, None) for a in self._AXIS_ORDERS} return axes, kwargs @classmethod @@ -1172,7 +1172,7 @@ def to_dense(self): # Picklability def __getstate__(self): - meta = dict((k, getattr(self, k, None)) for k in self._metadata) + meta = {k: getattr(self, k, None) for k in self._metadata} return dict(_data=self._data, _typ=self._typ, _metadata=self._metadata, **meta) @@ -4277,8 +4277,8 @@ def fillna(self, value=None, method=None, axis=None, inplace=False, elif self.ndim == 3: # fill in 2d chunks - result = dict((col, s.fillna(method=method, value=value)) - for col, s in self.iteritems()) + result = {col: s.fillna(method=method, value=value) + for col, s in self.iteritems()} new_obj = self._constructor.\ from_dict(result).__finalize__(self) new_data = new_obj._data @@ -5681,7 +5681,7 @@ def align(self, other, join='outer', axis=None, level=None, copy=True, # this means other is a DataFrame, and we need to broadcast # self cons = self._constructor_expanddim - df = cons(dict((c, self) for c in other.columns), + df = cons({c: self for c in other.columns}, **other._construct_axes_dict()) return df._align_frame(other, join=join, axis=axis, level=level, copy=copy, @@ -5691,7 +5691,7 @@ def align(self, other, join='outer', axis=None, level=None, copy=True, # this means self is a DataFrame, and we need to broadcast # other cons = other._constructor_expanddim - df = cons(dict((c, other) for c in self.columns), + df = cons({c: other for c in self.columns}, **self._construct_axes_dict()) return self._align_frame(df, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 8338df33f5cde..ba180cc98cb08 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -3840,7 +3840,7 @@ def first_not_none(values): # if all series have a consistent name. If the # series do not have a consistent name, do # nothing. - names = set(v.name for v in values) + names = {v.name for v in values} if len(names) == 1: index.name = list(names)[0] diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 7a34e64724245..1cb40b3ecf255 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -732,7 +732,7 @@ def _coerce_to_ndarray(cls, data): def _get_attributes_dict(self): """ return an attributes dict for my class """ - return dict((k, getattr(self, k, None)) for k in self._attributes) + return {k: getattr(self, k, None) for k in self._attributes} def view(self, cls=None): @@ -1784,7 +1784,7 @@ def append(self, other): if not isinstance(obj, Index): raise TypeError('all inputs must be Index') - names = set(obj.name for obj in to_concat) + names = {obj.name for obj in to_concat} name = None if len(names) > 1 else self.name return self._concat(to_concat, name) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index c9bb8748abe7b..20b6c15781535 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1003,7 +1003,7 @@ def _concat_same_dtype(self, to_concat, name): assert that we all have the same .closed we allow a 0-len index here as well """ - if not len(set(i.closed for i in to_concat if len(i))) == 1: + if not len({i.closed for i in to_concat if len(i)}) == 1: msg = ('can only append two IntervalIndex objects ' 'that are closed on the same side') raise ValueError(msg) diff --git a/pandas/core/internals.py b/pandas/core/internals.py index ca4984cc16673..e537cb2edc1c4 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -3377,7 +3377,7 @@ def reduction(self, f, axis=0, consolidate=True, transposed=False, blocks.append(block) # note that some DatetimeTZ, Categorical are always ndim==1 - ndim = set(b.ndim for b in blocks) + ndim = {b.ndim for b in blocks} if 2 in ndim: @@ -3891,7 +3891,7 @@ def get_scalar(self, tup): """ Retrieve single item """ - full_loc = list(ax.get_loc(x) for ax, x in zip(self.axes, tup)) + full_loc = [ax.get_loc(x) for ax, x in zip(self.axes, tup)] blk = self.blocks[self._blknos[full_loc[0]]] values = blk.values @@ -4871,7 +4871,7 @@ def _merge_blocks(blocks, dtype=None, _can_consolidate=True): if _can_consolidate: if dtype is None: - if len(set(b.dtype for b in blocks)) != 1: + if len({b.dtype for b in blocks}) != 1: raise AssertionError("_merge_blocks are invalid!") dtype = blocks[0].dtype diff --git a/pandas/core/ops.py b/pandas/core/ops.py index fa50036b6eb95..934570602c99d 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -146,7 +146,7 @@ def names(x): construct_result=_construct_divmod_result, ) - new_methods = dict((names(k), v) for k, v in new_methods.items()) + new_methods = {names(k): v for k, v in new_methods.items()} return new_methods diff --git a/pandas/core/panelnd.py b/pandas/core/panelnd.py index 691787125043d..80ee680d2b9d2 100644 --- a/pandas/core/panelnd.py +++ b/pandas/core/panelnd.py @@ -105,7 +105,7 @@ def _combine_with_constructor(self, other, func): new_axes.append(getattr(self, a).union(getattr(other, a))) # reindex: could check that everything's the same size, but forget it - d = dict((a, ax) for a, ax in zip(self._AXIS_ORDERS, new_axes)) + d = {a: ax for a, ax in zip(self._AXIS_ORDERS, new_axes)} d['copy'] = False this = self.reindex(**d) other = other.reindex(**d) diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 6139f093202fe..9bd5abb2cd476 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -568,7 +568,7 @@ def _make_concat_multiindex(indexes, keys, levels=None, names=None): names = list(names) else: # make sure that all of the passed indices have the same nlevels - if not len(set(idx.nlevels for idx in indexes)) == 1: + if not len({idx.nlevels for idx in indexes}) == 1: raise AssertionError("Cannot concat indices that do" " not have the same number of levels") diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 36e52f1472f82..16439b30d5bb4 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -149,7 +149,7 @@ def lreshape(data, groups, dropna=True, label=None): for c in pivot_cols: mask &= notna(mdata[c]) if not mask.all(): - mdata = dict((k, v[mask]) for k, v in compat.iteritems(mdata)) + mdata = {k: v[mask] for k, v in compat.iteritems(mdata)} from pandas import DataFrame return DataFrame(mdata, columns=id_cols + pivot_cols) diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py index 0c9a55e0c9acd..36a18d8f8b4a0 100644 --- a/pandas/core/sparse/frame.py +++ b/pandas/core/sparse/frame.py @@ -131,8 +131,7 @@ def _init_dict(self, data, index, columns, dtype=None): # pre-filter out columns if we passed it if columns is not None: columns = _ensure_index(columns) - data = dict((k, v) for k, v in compat.iteritems(data) - if k in columns) + data = {k: v for k, v in compat.iteritems(data) if k in columns} else: columns = Index(_try_sort(list(data.keys()))) @@ -173,7 +172,7 @@ def _init_matrix(self, data, index, columns, dtype=None): """ Init self from ndarray or list of lists """ data = _prep_ndarray(data, copy=False) index, columns = self._prep_index(data, index, columns) - data = dict((idx, data[:, i]) for i, idx in enumerate(columns)) + data = {idx: data[:, i] for i, idx in enumerate(columns)} return self._init_dict(data, index, columns, dtype) def _init_spmatrix(self, data, index, columns, dtype=None, @@ -307,7 +306,7 @@ def to_dense(self): ------- df : DataFrame """ - data = dict((k, v.to_dense()) for k, v in compat.iteritems(self)) + data = {k: v.to_dense() for k, v in compat.iteritems(self)} return DataFrame(data, index=self.index, columns=self.columns) def _apply_columns(self, func): @@ -697,7 +696,7 @@ def _reindex_columns(self, columns, method, copy, level, fill_value=None, raise NotImplementedError("'method' argument is not supported") # TODO: fill value handling - sdict = dict((k, v) for k, v in compat.iteritems(self) if k in columns) + sdict = {k: v for k, v in compat.iteritems(self) if k in columns} return self._constructor( sdict, index=self.index, columns=columns, default_fill_value=self._default_fill_value).__finalize__(self) diff --git a/pandas/io/clipboards.py b/pandas/io/clipboards.py index 117c96d00171c..8e9b5497083f6 100644 --- a/pandas/io/clipboards.py +++ b/pandas/io/clipboards.py @@ -53,7 +53,7 @@ def read_clipboard(sep='\s+', **kwargs): # pragma: no cover # 0 1 2 # 1 3 4 - counts = set(x.lstrip().count('\t') for x in lines) + counts = {x.lstrip().count('\t') for x in lines} if len(lines) > 1 and len(counts) == 1 and counts.pop() != 0: sep = '\t' diff --git a/pandas/io/json/json.py b/pandas/io/json/json.py index 32bab09a0c4ac..11bf3a9363953 100644 --- a/pandas/io/json/json.py +++ b/pandas/io/json/json.py @@ -715,10 +715,8 @@ def _parse_no_numpy(self): json = self.json orient = self.orient if orient == "split": - decoded = dict((str(k), v) - for k, v in compat.iteritems(loads( - json, - precise_float=self.precise_float))) + decoded = {str(k): v for k, v in compat.iteritems( + loads(json, precise_float=self.precise_float))} self.check_keys_split(decoded) self.obj = Series(dtype=None, **decoded) else: @@ -732,7 +730,7 @@ def _parse_numpy(self): if orient == "split": decoded = loads(json, dtype=None, numpy=True, precise_float=self.precise_float) - decoded = dict((str(k), v) for k, v in compat.iteritems(decoded)) + decoded = {str(k): v for k, v in compat.iteritems(decoded)} self.check_keys_split(decoded) self.obj = Series(**decoded) elif orient == "columns" or orient == "index": @@ -770,7 +768,7 @@ def _parse_numpy(self): elif orient == "split": decoded = loads(json, dtype=None, numpy=True, precise_float=self.precise_float) - decoded = dict((str(k), v) for k, v in compat.iteritems(decoded)) + decoded = {str(k): v for k, v in compat.iteritems(decoded)} self.check_keys_split(decoded) self.obj = DataFrame(**decoded) elif orient == "values": @@ -790,10 +788,8 @@ def _parse_no_numpy(self): self.obj = DataFrame( loads(json, precise_float=self.precise_float), dtype=None) elif orient == "split": - decoded = dict((str(k), v) - for k, v in compat.iteritems(loads( - json, - precise_float=self.precise_float))) + decoded = {str(k): v for k, v in compat.iteritems( + loads(json, precise_float=self.precise_float))} self.check_keys_split(decoded) self.obj = DataFrame(dtype=None, **decoded) elif orient == "index": diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 558a1f6d76868..8f6b013558396 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1133,8 +1133,7 @@ def _evaluate_usecols(usecols, names): If not a callable, returns 'usecols'. """ if callable(usecols): - return set(i for i, name in enumerate(names) - if usecols(name)) + return {i for i, name in enumerate(names) if usecols(name)} return usecols @@ -1906,7 +1905,7 @@ def read(self, nrows=None): # rename dict keys data = sorted(data.items()) - data = dict((k, v) for k, (i, v) in zip(names, data)) + data = {k: v for k, (i, v) in zip(names, data)} names, data = self._do_date_conversions(names, data) @@ -1924,7 +1923,7 @@ def read(self, nrows=None): # columns as list alldata = [x[1] for x in data] - data = dict((k, v) for k, (i, v) in zip(names, data)) + data = {k: v for k, (i, v) in zip(names, data)} names, data = self._do_date_conversions(names, data) index, names = self._make_index(data, alldata, names) @@ -2300,7 +2299,7 @@ def _exclude_implicit_index(self, alldata): offset += 1 data[col] = alldata[i + offset] else: - data = dict((k, v) for k, v in zip(names, alldata)) + data = {k: v for k, v in zip(names, alldata)} return data @@ -3233,9 +3232,8 @@ def _get_empty_meta(columns, index_col, index_names, dtype=None): for i, n in enumerate(index_col): columns.pop(n - i) - col_dict = dict((col_name, - Series([], dtype=dtype[col_name])) - for col_name in columns) + col_dict = {col_name: Series([], dtype=dtype[col_name]) + for col_name in columns} return index, columns, col_dict diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index b9cddce55c096..2a66aea88f6d9 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -815,7 +815,7 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None, "all tables must have exactly the same nrows!") # axis is the concentation axes - axis = list(set(t.non_index_axes[0][0] for t in tbls))[0] + axis = list({t.non_index_axes[0][0] for t in tbls})[0] def func(_start, _stop, _where): @@ -2374,8 +2374,7 @@ class GenericFixed(Fixed): """ a generified fixed version """ _index_type_map = {DatetimeIndex: 'datetime', PeriodIndex: 'period'} - _reverse_index_map = dict((v, k) - for k, v in compat.iteritems(_index_type_map)) + _reverse_index_map = {v: k for k, v in compat.iteritems(_index_type_map)} attributes = [] # indexer helpders @@ -3510,8 +3509,8 @@ def get_blk_items(mgr, blocks): # reorder the blocks in the same order as the existing_table if we can if existing_table is not None: - by_items = dict((tuple(b_items.tolist()), (b, b_items)) - for b, b_items in zip(blocks, blk_items)) + by_items = {tuple(b_items.tolist()): (b, b_items) + for b, b_items in zip(blocks, blk_items)} new_blocks = [] new_blk_items = [] for ea in existing_table.values_axes: @@ -3659,7 +3658,7 @@ def create_description(self, complib=None, complevel=None, d = dict(name='table', expectedrows=expectedrows) # description from the axes & values - d['description'] = dict((a.cname, a.typ) for a in self.axes) + d['description'] = {a.cname: a.typ for a in self.axes} if complib: if complevel is None: diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 401a9c11a774d..975ad1e4ff368 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -641,7 +641,7 @@ def insert_data(self): return column_names, data_list def _execute_insert(self, conn, keys, data_iter): - data = [dict((k, v) for k, v in zip(keys, row)) for row in data_iter] + data = [{k: v for k, v in zip(keys, row)} for row in data_iter] conn.execute(self.insert_statement(), data) def insert(self, chunksize=None): diff --git a/pandas/plotting/_converter.py b/pandas/plotting/_converter.py index 0f06d87726905..9daee918b9f30 100644 --- a/pandas/plotting/_converter.py +++ b/pandas/plotting/_converter.py @@ -994,7 +994,7 @@ def _set_default_format(self, vmin, vmax): info) else: format = np.compress(info['maj'], info) - self.formatdict = dict((x, f) for (x, _, _, f) in format) + self.formatdict = {x: f for (x, _, _, f) in format} return self.formatdict def set_locs(self, locs): diff --git a/pandas/tests/frame/common.py b/pandas/tests/frame/common.py index 3786facdd4ebd..c85fea3c3d71b 100644 --- a/pandas/tests/frame/common.py +++ b/pandas/tests/frame/common.py @@ -10,8 +10,8 @@ _frame = pd.DataFrame(_seriesd) _frame2 = pd.DataFrame(_seriesd, columns=['D', 'C', 'B', 'A']) -_intframe = pd.DataFrame(dict((k, v.astype(int)) - for k, v in compat.iteritems(_seriesd))) +_intframe = pd.DataFrame({k: v.astype(int) + for k, v in compat.iteritems(_seriesd)}) _tsframe = pd.DataFrame(_tsd) @@ -32,8 +32,7 @@ def frame2(self): @cache_readonly def intframe(self): # force these all to int64 to avoid platform testing issues - return pd.DataFrame(dict((c, s) for c, s in - compat.iteritems(_intframe)), + return pd.DataFrame({c: s for c, s in compat.iteritems(_intframe)}, dtype=np.int64) @cache_readonly @@ -112,7 +111,7 @@ def _check_mixed_float(df, dtype=None): # float16 are most likely to be upcasted to float32 dtypes = dict(A='float32', B='float32', C='float16', D='float64') if isinstance(dtype, compat.string_types): - dtypes = dict((k, dtype) for k, v in dtypes.items()) + dtypes = {k: dtype for k, v in dtypes.items()} elif isinstance(dtype, dict): dtypes.update(dtype) if dtypes.get('A'): @@ -128,7 +127,7 @@ def _check_mixed_float(df, dtype=None): def _check_mixed_int(df, dtype=None): dtypes = dict(A='int32', B='uint64', C='uint8', D='int64') if isinstance(dtype, compat.string_types): - dtypes = dict((k, dtype) for k, v in dtypes.items()) + dtypes = {k: dtype for k, v in dtypes.items()} elif isinstance(dtype, dict): dtypes.update(dtype) if dtypes.get('A'): diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index c50aa858a15b5..e81e31b718498 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -234,7 +234,7 @@ def test_itertuples(self): if sys.version >= LooseVersion('2.7'): assert tup2._fields == ('Index', '_1', '_2') - df3 = DataFrame(dict(('f' + str(i), [i]) for i in range(1024))) + df3 = DataFrame({'f' + str(i): [i] for i in range(1024)}) # will raise SyntaxError if trying to create namedtuple tup3 = next(df3.itertuples()) assert not hasattr(tup3, '_fields') diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 6ca90d715cb0b..2f947527ce95b 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -120,7 +120,7 @@ def _make_mixed_dtypes_df(typ, ad=None): assert(a.dtype == d) if ad is None: ad = dict() - ad.update(dict((d, a) for d, a in zipper)) + ad.update({d: a for d, a in zipper}) return DataFrame(ad) def _check_mixed_dtypes(df, dtypes=None): @@ -349,8 +349,8 @@ def test_constructor_subclass_dict(self): data = {'col1': tm.TestSubDict((x, 10.0 * x) for x in range(10)), 'col2': tm.TestSubDict((x, 20.0 * x) for x in range(10))} df = DataFrame(data) - refdf = DataFrame(dict((col, dict(compat.iteritems(val))) - for col, val in compat.iteritems(data))) + refdf = DataFrame({col: dict(compat.iteritems(val)) + for col, val in compat.iteritems(data)}) tm.assert_frame_equal(refdf, df) data = tm.TestSubDict(compat.iteritems(data)) @@ -413,8 +413,7 @@ def test_constructor_dict_of_tuples(self): data = {'a': (1, 2, 3), 'b': (4, 5, 6)} result = DataFrame(data) - expected = DataFrame(dict((k, list(v)) - for k, v in compat.iteritems(data))) + expected = DataFrame({k: list(v) for k, v in compat.iteritems(data)}) tm.assert_frame_equal(result, expected, check_dtype=False) def test_constructor_dict_multiindex(self): @@ -447,8 +446,8 @@ def test_constructor_dict_datetime64_index(self): dates_as_str = ['1984-02-19', '1988-11-06', '1989-12-03', '1990-03-15'] def create_data(constructor): - return dict((i, {constructor(s): 2 * i}) - for i, s in enumerate(dates_as_str)) + return {i: {constructor(s): 2 * i} + for i, s in enumerate(dates_as_str)} data_datetime64 = create_data(np.datetime64) data_datetime = create_data(lambda x: datetime.strptime(x, '%Y-%m-%d')) @@ -472,8 +471,8 @@ def test_constructor_dict_timedelta64_index(self): td_as_int = [1, 2, 3, 4] def create_data(constructor): - return dict((i, {constructor(s): 2 * i}) - for i, s in enumerate(td_as_int)) + return {i: {constructor(s): 2 * i} + for i, s in enumerate(td_as_int)} data_timedelta64 = create_data(lambda x: np.timedelta64(x, 'D')) data_timedelta = create_data(lambda x: timedelta(days=x)) @@ -696,8 +695,8 @@ def test_constructor_mrecarray(self): mrecs = mrecords.fromarrays(data, names=names) # fill the comb - comb = dict((k, v.filled()) if hasattr( - v, 'filled') else (k, v) for k, v in comb) + comb = {k: (v.filled() if hasattr(v, 'filled') else v) + for k, v in comb} expected = DataFrame(comb, columns=names) result = DataFrame(mrecs) @@ -1854,8 +1853,8 @@ def test_from_records_dictlike(self): for dtype, b in compat.iteritems(blocks): columns.extend(b.columns) - asdict = dict((x, y) for x, y in compat.iteritems(df)) - asdict2 = dict((x, y.values) for x, y in compat.iteritems(df)) + asdict = {x: y for x, y in compat.iteritems(df)} + asdict2 = {x: y.values for x, y in compat.iteritems(df)} # dict of series & dict of ndarrays (have dtype info) results = [] diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 91a5569b352e9..81153e83471cd 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -257,7 +257,7 @@ def test_len(self): assert len(grouped) == len(df) grouped = df.groupby([lambda x: x.year, lambda x: x.month]) - expected = len(set((x.year, x.month) for x in df.index)) + expected = len({(x.year, x.month) for x in df.index}) assert len(grouped) == expected # issue 11016 diff --git a/pandas/tests/groupby/test_whitelist.py b/pandas/tests/groupby/test_whitelist.py index 977c639d79711..de0deb442e516 100644 --- a/pandas/tests/groupby/test_whitelist.py +++ b/pandas/tests/groupby/test_whitelist.py @@ -238,7 +238,7 @@ def test_groupby_blacklist(df_letters): def test_tab_completion(mframe): grp = mframe.groupby(level='second') - results = set(v for v in dir(grp) if not v.startswith('_')) + results = {v for v in dir(grp) if not v.startswith('_')} expected = { 'A', 'B', 'C', 'agg', 'aggregate', 'apply', 'boxplot', 'filter', 'first', 'get_group', 'groups', 'hist', 'indices', 'last', 'max', diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 506a9e1c64b10..2f8c27f1abb7d 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -2178,7 +2178,7 @@ def check(nlevels, with_nulls): if with_nulls: # inject some null values labels[500] = -1 # common nan value - labels = list(labels.copy() for i in range(nlevels)) + labels = [labels.copy() for i in range(nlevels)] for i in range(nlevels): labels[i][500 + i - nlevels // 2] = -1 @@ -2773,7 +2773,7 @@ def test_groupby(self): # GH5620 groups = self.index.groupby(self.index) - exp = dict((key, [key]) for key in self.index) + exp = {key: [key] for key in self.index} tm.assert_dict_equal(groups, exp) def test_index_name_retained(self): diff --git a/pandas/tests/indexing/test_panel.py b/pandas/tests/indexing/test_panel.py index 4d7768c9e8083..c4f7bd28e4d90 100644 --- a/pandas/tests/indexing/test_panel.py +++ b/pandas/tests/indexing/test_panel.py @@ -119,7 +119,7 @@ def test_panel_getitem(self): df = DataFrame( np.random.randn( len(ind), 5), index=ind, columns=list('ABCDE')) - panel = Panel(dict(('frame_' + c, df) for c in list('ABC'))) + panel = Panel({'frame_' + c: df for c in list('ABC')}) test2 = panel.loc[:, "2002":"2002-12-31"] test1 = panel.loc[:, "2002"] diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 47632b1399991..6553dd66cba5f 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1505,11 +1505,11 @@ def test_repr_html_long_and_wide(self): max_rows = get_option('display.max_rows') h, w = max_rows - 1, max_cols - 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert '...' not in df._repr_html_() h, w = max_rows + 1, max_cols + 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert '...' in df._repr_html_() def test_info_repr(self): @@ -1517,14 +1517,14 @@ def test_info_repr(self): max_cols = get_option('display.max_columns') # Long h, w = max_rows + 1, max_cols - 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert has_vertically_truncated_repr(df) with option_context('display.large_repr', 'info'): assert has_info_repr(df) # Wide h, w = max_rows - 1, max_cols + 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert has_horizontally_truncated_repr(df) with option_context('display.large_repr', 'info'): assert has_info_repr(df) @@ -1550,14 +1550,14 @@ def test_info_repr_html(self): max_cols = get_option('display.max_columns') # Long h, w = max_rows + 1, max_cols - 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert r'<class' not in df._repr_html_() with option_context('display.large_repr', 'info'): assert r'<class' in df._repr_html_() # Wide h, w = max_rows - 1, max_cols + 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert ' Date: Mon, 20 Nov 2017 10:12:46 -0800 Subject: [PATCH 2/4] Simplify series plotting test Extra lint --- pandas/tests/plotting/test_series.py | 5 ++--- versioneer.py | 12 ++++++------ 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 99750992ce30a..fdfd87d1e898c 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -3,7 +3,7 @@ """ Test cases for Series.plot """ -import itertools +from itertools import chain import pytest from datetime import datetime @@ -333,8 +333,7 @@ def test_pie_series(self): autopct='%.2f', fontsize=7) pcts = ['{0:.2f}'.format(s * 100) for s in series.values / float(series.sum())] - iters = [iter(series.index), iter(pcts)] - expected_texts = [next(it) for it in itertools.cycle(iters)] + expected_texts = list(chain.from_iterable(zip(series.index, pcts))) self._check_text_labels(ax.texts, expected_texts) for t in ax.texts: assert t.get_fontsize() == 7 diff --git a/versioneer.py b/versioneer.py index 59228ec63c136..b0ae4fa2dc8e8 100644 --- a/versioneer.py +++ b/versioneer.py @@ -606,11 +606,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set(r.strip() for r in refnames.strip("()").split(",")) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d @@ -619,7 +619,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set(r for r in refs if re.search(r'\d', r)) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%%s', no digits" %% ",".join(refs-tags)) if verbose: @@ -960,11 +960,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set(r.strip() for r in refnames.strip("()").split(",")) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -973,7 +973,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set(r for r in refs if re.search(r'\d', r)) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) if verbose: From 31446b7d0a55b795e240495dc9861fc20d20115a Mon Sep 17 00:00:00 2001 From: Matt Roeschke Date: Wed, 22 Nov 2017 11:09:18 -0800 Subject: [PATCH 3/4] add path to grep --- ci/lint.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ci/lint.sh b/ci/lint.sh index c1722e2b99e3e..b45b7133949b9 100755 --- a/ci/lint.sh +++ b/ci/lint.sh @@ -90,7 +90,7 @@ if [ "$LINT" ]; then # # Check the following functions: # any(), all(), sum(), max(), min(), list(), dict(), set(), frozenset(), tuple(), str.join() - grep -R --include="*.py*" -E "[^_](any|all|sum|max|min|list|dict|set|frozenset|tuple|join)\(\[.* for .* in .*\]\)" + grep -R --include="*.py*" -E "[^_](any|all|sum|max|min|list|dict|set|frozenset|tuple|join)\(\[.* for .* in .*\]\)" . if [ $? = "0" ]; then RET=1 @@ -103,7 +103,7 @@ if [ "$LINT" ]; then # # Check the following functions: # list(), set(), dict() - grep -R --include="*.py*" -E "(list|dict|[^frozen]set)\([^\{)=]* for .* in [^}]*\)" + grep -R --include="*.py*" -E "(list|dict|[^frozen]set)\([^\{)=]* for .* in [^}]*\)" . if [ $? = "0" ]; then RET=1 From 371c22f0142d8b679465719117d68b65b99e0f09 Mon Sep 17 00:00:00 2001 From: Matt Roeschke Date: Thu, 23 Nov 2017 17:13:06 -0800 Subject: [PATCH 4/4] Remove lint rule; postpone to new issue --- ci/lint.sh | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/ci/lint.sh b/ci/lint.sh index b45b7133949b9..4027737900bf9 100755 --- a/ci/lint.sh +++ b/ci/lint.sh @@ -90,26 +90,13 @@ if [ "$LINT" ]; then # # Check the following functions: # any(), all(), sum(), max(), min(), list(), dict(), set(), frozenset(), tuple(), str.join() - grep -R --include="*.py*" -E "[^_](any|all|sum|max|min|list|dict|set|frozenset|tuple|join)\(\[.* for .* in .*\]\)" . + grep -R --include="*.py*" -E "[^_](any|all|sum|max|min|list|dict|set|frozenset|tuple|join)\(\[.* for .* in .*\]\)" if [ $? = "0" ]; then RET=1 fi echo "Check for use of lists instead of generators in built-in Python functions DONE" - echo "Check for use of comprehensions using set(), dict() or list()" - - # Example: Avoid `list(i for i in some_iterator)` in favor of `[i for i in some_iterator]` - # - # Check the following functions: - # list(), set(), dict() - grep -R --include="*.py*" -E "(list|dict|[^frozen]set)\([^\{)=]* for .* in [^}]*\)" . - - if [ $? = "0" ]; then - RET=1 - fi - echo "Check for use of comprehensions using set(), dict() or list() DONE" - else echo "NOT Linting" fi