Skip to content

Commit 0825e5d

Browse files
mroeschkeim-vinicius
authored and
im-vinicius
committed
STY: Enable ruff C4 - comprehensions (pandas-dev#53056)
* STY: Enable ruff C4 - comprehensions * Revert one
1 parent 3df21c5 commit 0825e5d

File tree

22 files changed

+41
-42
lines changed

22 files changed

+41
-42
lines changed

asv_bench/benchmarks/dtypes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424

2525

2626
class Dtypes:
27-
params = _dtypes + list(map(lambda dt: dt.name, _dtypes))
27+
params = _dtypes + [dt.name for dt in _dtypes]
2828
param_names = ["dtype"]
2929

3030
def time_pandas_dtype(self, dtype):

pandas/core/computation/expr.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ def _filter_nodes(superclass, all_nodes=_all_nodes):
192192
return frozenset(node_names)
193193

194194

195-
_all_node_names = frozenset(map(lambda x: x.__name__, _all_nodes))
195+
_all_node_names = frozenset(x.__name__ for x in _all_nodes)
196196
_mod_nodes = _filter_nodes(ast.mod)
197197
_stmt_nodes = _filter_nodes(ast.stmt)
198198
_expr_nodes = _filter_nodes(ast.expr)

pandas/core/groupby/groupby.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -4115,9 +4115,9 @@ def _reindex_output(
41154115
# reindex `output`, and then reset the in-axis grouper columns.
41164116

41174117
# Select in-axis groupers
4118-
in_axis_grps = list(
4118+
in_axis_grps = [
41194119
(i, ping.name) for (i, ping) in enumerate(groupings) if ping.in_axis
4120-
)
4120+
]
41214121
if len(in_axis_grps) > 0:
41224122
g_nums, g_names = zip(*in_axis_grps)
41234123
output = output.drop(labels=list(g_names), axis=1)

pandas/io/formats/excel.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -726,7 +726,7 @@ def _format_header(self) -> Iterable[ExcelCell]:
726726
row = [x if x is not None else "" for x in self.df.index.names] + [
727727
""
728728
] * len(self.columns)
729-
if reduce(lambda x, y: x and y, map(lambda x: x != "", row)):
729+
if reduce(lambda x, y: x and y, (x != "" for x in row)):
730730
gen2 = (
731731
ExcelCell(self.rowcounter, colindex, val, self.header_style)
732732
for colindex, val in enumerate(row)

pandas/io/formats/html.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -621,7 +621,7 @@ def write_style(self) -> None:
621621
)
622622
else:
623623
element_props.append(("thead th", "text-align", "right"))
624-
template_mid = "\n\n".join(map(lambda t: template_select % t, element_props))
624+
template_mid = "\n\n".join(template_select % t for t in element_props)
625625
template = dedent("\n".join((template_first, template_mid, template_last)))
626626
self.write(template)
627627

pandas/tests/computation/test_eval.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def test_compound_invert_op(self, op, lhs, rhs, request, engine, parser):
218218
else:
219219
# compound
220220
if is_scalar(lhs) and is_scalar(rhs):
221-
lhs, rhs = map(lambda x: np.array([x]), (lhs, rhs))
221+
lhs, rhs = (np.array([x]) for x in (lhs, rhs))
222222
expected = _eval_single_bin(lhs, op, rhs, engine)
223223
if is_scalar(expected):
224224
expected = not expected
@@ -746,7 +746,7 @@ def test_binop_typecasting(self, engine, parser, op, dt, left_right):
746746
def should_warn(*args):
747747
not_mono = not any(map(operator.attrgetter("is_monotonic_increasing"), args))
748748
only_one_dt = reduce(
749-
operator.xor, map(lambda x: issubclass(x.dtype.type, np.datetime64), args)
749+
operator.xor, (issubclass(x.dtype.type, np.datetime64) for x in args)
750750
)
751751
return not_mono and only_one_dt
752752

pandas/tests/dtypes/test_missing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -643,7 +643,7 @@ def test_array_equivalent_nested_mixed_list(strict_nan):
643643
np.array(["c", "d"], dtype=object),
644644
]
645645
left = np.array([subarr, None], dtype=object)
646-
right = np.array([list([[None, "b"], ["c", "d"]]), None], dtype=object)
646+
right = np.array([[[None, "b"], ["c", "d"]], None], dtype=object)
647647
assert array_equivalent(left, right, strict_nan=strict_nan)
648648
assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
649649

pandas/tests/extension/date/array.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def __init__(
8383
self._day = np.zeros(ldates, dtype=np.uint8) # 255 (1, 12)
8484
# populate them
8585
for i, (y, m, d) in enumerate(
86-
map(lambda date: (date.year, date.month, date.day), dates)
86+
(date.year, date.month, date.day) for date in dates
8787
):
8888
self._year[i] = y
8989
self._month[i] = m
@@ -94,7 +94,7 @@ def __init__(
9494
if ldates != 3:
9595
raise ValueError("only triples are valid")
9696
# check if all elements have the same type
97-
if any(map(lambda x: not isinstance(x, np.ndarray), dates)):
97+
if any(not isinstance(x, np.ndarray) for x in dates):
9898
raise TypeError("invalid type")
9999
ly, lm, ld = (len(cast(np.ndarray, d)) for d in dates)
100100
if not ly == lm == ld:

pandas/tests/frame/methods/test_astype.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,9 @@ def test_astype_str(self):
152152

153153
expected = DataFrame(
154154
{
155-
"a": list(map(str, map(lambda x: Timestamp(x)._date_repr, a._values))),
155+
"a": list(map(str, (Timestamp(x)._date_repr for x in a._values))),
156156
"b": list(map(str, map(Timestamp, b._values))),
157-
"c": list(map(lambda x: Timedelta(x)._repr_base(), c._values)),
157+
"c": [Timedelta(x)._repr_base() for x in c._values],
158158
"d": list(map(str, d._values)),
159159
"e": list(map(str, e._values)),
160160
}

pandas/tests/groupby/test_grouping.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -992,7 +992,7 @@ def test_multi_iter_frame(self, three_group):
992992
# calling `dict` on a DataFrameGroupBy leads to a TypeError,
993993
# we need to use a dictionary comprehension here
994994
# pylint: disable-next=unnecessary-comprehension
995-
groups = {key: gp for key, gp in grouped}
995+
groups = {key: gp for key, gp in grouped} # noqa: C416
996996
assert len(groups) == 2
997997

998998
# axis = 1

pandas/tests/groupby/test_raises.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ def test_groupby_raises_string_np(
229229
),
230230
}[groupby_func_np]
231231

232-
_call_and_check(klass, msg, how, gb, groupby_func_np, tuple())
232+
_call_and_check(klass, msg, how, gb, groupby_func_np, ())
233233

234234

235235
@pytest.mark.parametrize("how", ["method", "agg", "transform"])
@@ -333,7 +333,7 @@ def test_groupby_raises_datetime_np(
333333
np.mean: (None, ""),
334334
}[groupby_func_np]
335335

336-
_call_and_check(klass, msg, how, gb, groupby_func_np, tuple())
336+
_call_and_check(klass, msg, how, gb, groupby_func_np, ())
337337

338338

339339
@pytest.mark.parametrize("func", ["prod", "cumprod", "skew", "var"])
@@ -526,7 +526,7 @@ def test_groupby_raises_category_np(
526526
),
527527
}[groupby_func_np]
528528

529-
_call_and_check(klass, msg, how, gb, groupby_func_np, tuple())
529+
_call_and_check(klass, msg, how, gb, groupby_func_np, ())
530530

531531

532532
@pytest.mark.parametrize("how", ["method", "agg", "transform"])

pandas/tests/groupby/transform/test_transform.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -362,11 +362,11 @@ def test_dispatch_transform(tsframe):
362362

363363
def test_transform_fillna_null():
364364
df = DataFrame(
365-
dict(
366-
price=[10, 10, 20, 20, 30, 30],
367-
color=[10, 10, 20, 20, 30, 30],
368-
cost=(100, 200, 300, 400, 500, 600),
369-
)
365+
{
366+
"price": [10, 10, 20, 20, 30, 30],
367+
"color": [10, 10, 20, 20, 30, 30],
368+
"cost": (100, 200, 300, 400, 500, 600),
369+
}
370370
)
371371
with pytest.raises(ValueError, match="Must specify a fill 'value' or 'method'"):
372372
df.groupby(["price"]).transform("fillna")

pandas/tests/indexing/multiindex/test_indexing_slow.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
np.random.choice(list("ZYXWVUTSRQP"), m),
3535
]
3636
keys = list(map(tuple, zip(*keys)))
37-
keys += list(map(lambda t: t[:-1], vals[:: n // m]))
37+
keys += [t[:-1] for t in vals[:: n // m]]
3838

3939

4040
# covers both unique index and non-unique index

pandas/tests/indexing/test_partial.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -283,30 +283,30 @@ def test_partial_setting_frame(self, using_array_manager):
283283
df.iat[4, 2] = 5.0
284284

285285
# row setting where it exists
286-
expected = DataFrame(dict({"A": [0, 4, 4], "B": [1, 5, 5]}))
286+
expected = DataFrame({"A": [0, 4, 4], "B": [1, 5, 5]})
287287
df = df_orig.copy()
288288
df.iloc[1] = df.iloc[2]
289289
tm.assert_frame_equal(df, expected)
290290

291-
expected = DataFrame(dict({"A": [0, 4, 4], "B": [1, 5, 5]}))
291+
expected = DataFrame({"A": [0, 4, 4], "B": [1, 5, 5]})
292292
df = df_orig.copy()
293293
df.loc[1] = df.loc[2]
294294
tm.assert_frame_equal(df, expected)
295295

296296
# like 2578, partial setting with dtype preservation
297-
expected = DataFrame(dict({"A": [0, 2, 4, 4], "B": [1, 3, 5, 5]}))
297+
expected = DataFrame({"A": [0, 2, 4, 4], "B": [1, 3, 5, 5]})
298298
df = df_orig.copy()
299299
df.loc[3] = df.loc[2]
300300
tm.assert_frame_equal(df, expected)
301301

302302
# single dtype frame, overwrite
303-
expected = DataFrame(dict({"A": [0, 2, 4], "B": [0, 2, 4]}))
303+
expected = DataFrame({"A": [0, 2, 4], "B": [0, 2, 4]})
304304
df = df_orig.copy()
305305
df.loc[:, "B"] = df.loc[:, "A"]
306306
tm.assert_frame_equal(df, expected)
307307

308308
# mixed dtype frame, overwrite
309-
expected = DataFrame(dict({"A": [0, 2, 4], "B": Series([0.0, 2.0, 4.0])}))
309+
expected = DataFrame({"A": [0, 2, 4], "B": Series([0.0, 2.0, 4.0])})
310310
df = df_orig.copy()
311311
df["B"] = df["B"].astype(np.float64)
312312
# as of 2.0, df.loc[:, "B"] = ... attempts (and here succeeds) at

pandas/tests/io/formats/style/test_html.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -978,7 +978,7 @@ def html_lines(foot_prefix: str):
978978

979979
def test_to_html_na_rep_non_scalar_data(datapath):
980980
# GH47103
981-
df = DataFrame([dict(a=1, b=[1, 2, 3], c=np.nan)])
981+
df = DataFrame([{"a": 1, "b": [1, 2, 3], "c": np.nan}])
982982
result = df.style.format(na_rep="-").to_html(table_uuid="test")
983983
expected = """\
984984
<style type="text/css">

pandas/tests/io/formats/style/test_matplotlib.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,7 @@ def test_pass_colormap_instance(df, plot_method):
307307
# https://github.com/pandas-dev/pandas/issues/49374
308308
cmap = mpl.colors.ListedColormap([[1, 1, 1], [0, 0, 0]])
309309
df["c"] = df.A + df.B
310-
kwargs = dict(x="A", y="B", c="c", colormap=cmap)
310+
kwargs = {"x": "A", "y": "B", "c": "c", "colormap": cmap}
311311
if plot_method == "hexbin":
312312
kwargs["C"] = kwargs.pop("c")
313313
getattr(df.plot, plot_method)(**kwargs)

pandas/tests/io/formats/test_to_html.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -884,7 +884,7 @@ def test_to_html_na_rep_and_float_format(na_rep, datapath):
884884

885885
def test_to_html_na_rep_non_scalar_data(datapath):
886886
# GH47103
887-
df = DataFrame([dict(a=1, b=[1, 2, 3])])
887+
df = DataFrame([{"a": 1, "b": [1, 2, 3]}])
888888
result = df.to_html(na_rep="-")
889889
expected = expected_html(datapath, "gh47103_expected_output")
890890
assert result == expected

pandas/tests/io/parser/test_parse_dates.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -746,9 +746,7 @@ def test_date_parser_int_bug(all_parsers):
746746
def test_nat_parse(all_parsers):
747747
# see gh-3062
748748
parser = all_parsers
749-
df = DataFrame(
750-
dict({"A": np.arange(10, dtype="float64"), "B": Timestamp("20010101")})
751-
)
749+
df = DataFrame({"A": np.arange(10, dtype="float64"), "B": Timestamp("20010101")})
752750
df.iloc[3:6, :] = np.nan
753751

754752
with tm.ensure_clean("__nat_parse_.csv") as path:

pandas/tests/libs/test_hashtable.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def get_allocated_khash_memory():
2828
snapshot = snapshot.filter_traces(
2929
(tracemalloc.DomainFilter(True, ht.get_hashtable_trace_domain()),)
3030
)
31-
return sum(map(lambda x: x.size, snapshot.traces))
31+
return sum(x.size for x in snapshot.traces)
3232

3333

3434
@pytest.mark.parametrize(

pandas/tests/series/test_constructors.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -369,14 +369,14 @@ def test_constructor_generator(self):
369369

370370
def test_constructor_map(self):
371371
# GH8909
372-
m = map(lambda x: x, range(10))
372+
m = (x for x in range(10))
373373

374374
result = Series(m)
375375
exp = Series(range(10))
376376
tm.assert_series_equal(result, exp)
377377

378378
# same but with non-default index
379-
m = map(lambda x: x, range(10))
379+
m = (x for x in range(10))
380380
result = Series(m, index=range(10, 20))
381381
exp.index = range(10, 20)
382382
tm.assert_series_equal(result, exp)
@@ -647,7 +647,7 @@ def test_constructor_default_index(self):
647647
list(range(3)),
648648
Categorical(["a", "b", "a"]),
649649
(i for i in range(3)),
650-
map(lambda x: x, range(3)),
650+
(x for x in range(3)),
651651
],
652652
)
653653
def test_constructor_index_mismatch(self, input):

pandas/tests/util/test_assert_almost_equal.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -512,7 +512,7 @@ def test_assert_almost_equal_iterable_values_mismatch():
512512
# same-length lists
513513
(
514514
np.array([subarr, None], dtype=object),
515-
np.array([list([[None, "b"], ["c", "d"]]), None], dtype=object),
515+
np.array([[[None, "b"], ["c", "d"]], None], dtype=object),
516516
),
517517
# dicts
518518
(

pyproject.toml

+4-3
Original file line numberDiff line numberDiff line change
@@ -195,14 +195,13 @@ line-length = 88
195195
update-check = false
196196
target-version = "py310"
197197
fix = true
198-
unfixable = ["E711"]
198+
unfixable = []
199199

200200
select = [
201201
# pyflakes
202202
"F",
203203
# pycodestyle
204-
"E",
205-
"W",
204+
"E", "W",
206205
# flake8-2020
207206
"YTT",
208207
# flake8-bugbear
@@ -221,6 +220,8 @@ select = [
221220
"ISC",
222221
# type-checking imports
223222
"TCH",
223+
# comprehensions
224+
"C4",
224225
]
225226

226227
ignore = [

0 commit comments

Comments
 (0)