Skip to content

Commit 2be9661

Browse files
fabincacarlotta
and
carlotta
authored
STYLE fix: pylint "consider-using-in" warning (#49213)
* consider-using-in * consider-using-in * remove consider using in from pyproject.toml to add it to pylint * after running pre-commit chacks Co-authored-by: carlotta <[email protected]>
1 parent 1ceaee3 commit 2be9661

31 files changed

+50
-57
lines changed

pandas/core/computation/pytables.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -211,15 +211,15 @@ def stringify(value):
211211

212212
kind = ensure_decoded(self.kind)
213213
meta = ensure_decoded(self.meta)
214-
if kind == "datetime64" or kind == "datetime":
214+
if kind in ("datetime64", "datetime"):
215215
if isinstance(v, (int, float)):
216216
v = stringify(v)
217217
v = ensure_decoded(v)
218218
v = Timestamp(v)
219219
if v.tz is not None:
220220
v = v.tz_convert("UTC")
221221
return TermValue(v, v.value, kind)
222-
elif kind == "timedelta64" or kind == "timedelta":
222+
elif kind in ("timedelta64", "timedelta"):
223223
if isinstance(v, str):
224224
v = Timedelta(v).value
225225
else:

pandas/core/frame.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1754,7 +1754,7 @@ def from_dict(
17541754
# error: Incompatible types in assignment (expression has type
17551755
# "List[Any]", variable has type "Dict[Any, Any]")
17561756
data = list(data.values()) # type: ignore[assignment]
1757-
elif orient == "columns" or orient == "tight":
1757+
elif orient in ("columns", "tight"):
17581758
if columns is not None:
17591759
raise ValueError(f"cannot use columns parameter with orient='{orient}'")
17601760
else: # pragma: no cover

pandas/core/indexes/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4066,7 +4066,7 @@ def _check_indexing_method(
40664066
"method='nearest' not implemented yet "
40674067
"for MultiIndex; see GitHub issue 9365"
40684068
)
4069-
elif method == "pad" or method == "backfill":
4069+
elif method in ("pad", "backfill"):
40704070
if tolerance is not None:
40714071
raise NotImplementedError(
40724072
"tolerance not implemented yet for MultiIndex"

pandas/core/indexes/datetimelike.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -663,7 +663,7 @@ def _get_insert_freq(self, loc: int, item):
663663
if self.size:
664664
if item is NaT:
665665
pass
666-
elif (loc == 0 or loc == -len(self)) and item + self.freq == self[0]:
666+
elif loc in (0, -len(self)) and item + self.freq == self[0]:
667667
freq = self.freq
668668
elif (loc == len(self)) and item - self.freq == self[-1]:
669669
freq = self.freq

pandas/core/indexes/range.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -833,11 +833,11 @@ def delete(self, loc) -> Index: # type: ignore[override]
833833
# In some cases we can retain RangeIndex, see also
834834
# DatetimeTimedeltaMixin._get_delete_Freq
835835
if is_integer(loc):
836-
if loc == 0 or loc == -len(self):
836+
if loc in (0, -len(self)):
837837
return self[1:]
838-
if loc == -1 or loc == len(self) - 1:
838+
if loc in (-1, len(self) - 1):
839839
return self[:-1]
840-
if len(self) == 3 and (loc == 1 or loc == -2):
840+
if len(self) == 3 and loc in (1, -2):
841841
return self[::2]
842842

843843
elif lib.is_list_like(loc):

pandas/core/nanops.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ def _bn_ok_dtype(dtype: DtypeObj, name: str) -> bool:
183183

184184
def _has_infs(result) -> bool:
185185
if isinstance(result, np.ndarray):
186-
if result.dtype == "f8" or result.dtype == "f4":
186+
if result.dtype in ("f8", "f4"):
187187
# Note: outside of an nanops-specific test, we always have
188188
# result.ndim == 1, so there is no risk of this ravel making a copy.
189189
return lib.has_infs(result.ravel("K"))

pandas/core/ops/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ def _maybe_align_series_as_frame(frame: DataFrame, series: Series, axis: AxisInt
397397
rvalues = series._values
398398
if not isinstance(rvalues, np.ndarray):
399399
# TODO(EA2D): no need to special-case with 2D EAs
400-
if rvalues.dtype == "datetime64[ns]" or rvalues.dtype == "timedelta64[ns]":
400+
if rvalues.dtype in ("datetime64[ns]", "timedelta64[ns]"):
401401
# We can losslessly+cheaply cast to ndarray
402402
rvalues = np.asarray(rvalues)
403403
else:

pandas/io/formats/excel.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ def _border_style(self, style: str | None, width: str | None, color: str | None)
277277
# Return "none" will keep "border" in style dictionary
278278
return "none"
279279

280-
if style == "none" or style == "hidden":
280+
if style in ("none", "hidden"):
281281
return "none"
282282

283283
width_name = self._get_width_name(width)

pandas/io/formats/style.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4210,7 +4210,7 @@ def css_calc(x, left: float, right: float, align: str, color: str | list | tuple
42104210
z, align = align(values), "zero"
42114211
elif isinstance(align, (float, int)):
42124212
z, align = float(align), "zero"
4213-
elif not (align == "left" or align == "right" or align == "zero"):
4213+
elif align not in ("left", "right", "zero"):
42144214
raise ValueError(
42154215
"`align` should be in {'left', 'right', 'mid', 'mean', 'zero'} or be a "
42164216
"value defining the center line or a callable that returns a float"

pandas/io/formats/style_render.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2228,14 +2228,14 @@ def _parse_latex_css_conversion(styles: CSSList) -> CSSList:
22282228
"""
22292229

22302230
def font_weight(value, arg):
2231-
if value == "bold" or value == "bolder":
2231+
if value in ("bold", "bolder"):
22322232
return "bfseries", f"{arg}"
22332233
return None
22342234

22352235
def font_style(value, arg):
22362236
if value == "italic":
22372237
return "itshape", f"{arg}"
2238-
elif value == "oblique":
2238+
if value == "oblique":
22392239
return "slshape", f"{arg}"
22402240
return None
22412241

pandas/io/html.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -527,7 +527,7 @@ def _expand_colspan_rowspan(
527527

528528
# Append the text from this <td>, colspan times
529529
text = _remove_whitespace(self._text_getter(td))
530-
if self.extract_links == "all" or self.extract_links == section:
530+
if self.extract_links in ("all", section):
531531
href = self._href_getter(td)
532532
text = (text, href)
533533
rowspan = int(self._attr_getter(td, "rowspan") or 1)

pandas/io/json/_json.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1146,7 +1146,7 @@ def _try_convert_data(
11461146
pass
11471147

11481148
# don't coerce 0-len data
1149-
if len(data) and (data.dtype == "float" or data.dtype == "object"):
1149+
if len(data) and data.dtype in ("float", "object"):
11501150

11511151
# coerce ints if we can
11521152
try:

pandas/io/parsers/python_parser.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -788,9 +788,9 @@ def _next_iter_line(self, row_num: int) -> list[Scalar] | None:
788788
assert isinstance(line, list)
789789
return line
790790
except csv.Error as e:
791-
if (
792-
self.on_bad_lines == self.BadLineHandleMethod.ERROR
793-
or self.on_bad_lines == self.BadLineHandleMethod.WARN
791+
if self.on_bad_lines in (
792+
self.BadLineHandleMethod.ERROR,
793+
self.BadLineHandleMethod.WARN,
794794
):
795795
msg = str(e)
796796

@@ -1013,9 +1013,9 @@ def _rows_to_cols(self, content: list[list[Scalar]]) -> list[np.ndarray]:
10131013
new_l = self.on_bad_lines(l)
10141014
if new_l is not None:
10151015
content.append(new_l)
1016-
elif (
1017-
self.on_bad_lines == self.BadLineHandleMethod.ERROR
1018-
or self.on_bad_lines == self.BadLineHandleMethod.WARN
1016+
elif self.on_bad_lines in (
1017+
self.BadLineHandleMethod.ERROR,
1018+
self.BadLineHandleMethod.WARN,
10191019
):
10201020
row_num = self.pos - (content_len - i + footers)
10211021
bad_lines.append((row_num, actual_len))

pandas/io/parsers/readers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2229,7 +2229,7 @@ def _merge_with_dialect_properties(
22292229

22302230
# Don't warn if the default parameter was passed in,
22312231
# even if it conflicts with the dialect (gh-23761).
2232-
if provided != parser_default and provided != dialect_val:
2232+
if provided not in (parser_default, dialect_val):
22332233
msg = (
22342234
f"Conflicting values for '{param}': '{provided}' was "
22352235
f"provided, but the dialect specifies '{dialect_val}'. "

pandas/io/pytables.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -618,7 +618,7 @@ def __contains__(self, key: str) -> bool:
618618
node = self.get_node(key)
619619
if node is not None:
620620
name = node._v_pathname
621-
if name == key or name[1:] == key:
621+
if key in (name, name[1:]):
622622
return True
623623
return False
624624

@@ -3006,7 +3006,7 @@ def read_index_node(
30063006
attrs = node._v_attrs
30073007
factory, kwargs = self._get_index_factory(attrs)
30083008

3009-
if kind == "date" or kind == "object":
3009+
if kind in ("date", "object"):
30103010
index = factory(
30113011
_unconvert_index(
30123012
data, kind, encoding=self.encoding, errors=self.errors
@@ -5243,7 +5243,7 @@ def __init__(
52435243
# see if we have a passed coordinate like
52445244
with suppress(ValueError):
52455245
inferred = lib.infer_dtype(where, skipna=False)
5246-
if inferred == "integer" or inferred == "boolean":
5246+
if inferred in ("integer", "boolean"):
52475247
where = np.asarray(where)
52485248
if where.dtype == np.bool_:
52495249
start, stop = self.start, self.stop

pandas/io/sas/sas7bdat.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -431,10 +431,7 @@ def _process_page_metadata(self) -> None:
431431
subheader_processor = self._subheader_processors[subheader_index]
432432

433433
if subheader_processor is None:
434-
f1 = (
435-
subheader_compression == const.compressed_subheader_id
436-
or subheader_compression == 0
437-
)
434+
f1 = subheader_compression in (const.compressed_subheader_id, 0)
438435
f2 = subheader_type == const.compressed_subheader_type
439436
if self.compression and f1 and f2:
440437
self._current_page_data_subheader_pointers.append(

pandas/io/sql.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1178,7 +1178,7 @@ def _sqlalchemy_type(self, col):
11781178
Time,
11791179
)
11801180

1181-
if col_type == "datetime64" or col_type == "datetime":
1181+
if col_type in ("datetime64", "datetime"):
11821182
# GH 9086: TIMESTAMP is the suggested type if the column contains
11831183
# timezone information
11841184
try:

pandas/io/stata.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2178,7 +2178,7 @@ def _dtype_to_default_stata_fmt(
21782178
return "%9.0g"
21792179
elif dtype == np.int32:
21802180
return "%12.0g"
2181-
elif dtype == np.int8 or dtype == np.int16:
2181+
elif dtype in (np.int8, np.int16):
21822182
return "%8.0g"
21832183
else: # pragma : no cover
21842184
raise NotImplementedError(f"Data type {dtype} not supported.")

pandas/tests/apply/test_frame_apply.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1342,7 +1342,7 @@ def test_size_as_str(how, axis):
13421342
# Just a string attribute arg same as calling df.arg
13431343
# on the columns
13441344
result = getattr(df, how)("size", axis=axis)
1345-
if axis == 0 or axis == "index":
1345+
if axis in (0, "index"):
13461346
expected = Series(df.shape[0], index=df.columns)
13471347
else:
13481348
expected = Series(df.shape[1], index=df.index)

pandas/tests/apply/test_frame_transform.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def test_transform_empty_listlike(float_frame, ops, frame_or_series):
6969
@pytest.mark.parametrize("box", [dict, Series])
7070
def test_transform_dictlike(axis, float_frame, box):
7171
# GH 35964
72-
if axis == 0 or axis == "index":
72+
if axis in (0, "index"):
7373
e = float_frame.columns[0]
7474
expected = float_frame[[e]].transform(np.abs)
7575
else:

pandas/tests/apply/test_str.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ def test_agg_cython_table_transform_frame(df, func, expected, axis):
236236
# GH 21224
237237
# test transforming functions in
238238
# pandas.core.base.SelectionMixin._cython_table (cumprod, cumsum)
239-
if axis == "columns" or axis == 1:
239+
if axis in ("columns", 1):
240240
# operating blockwise doesn't let us preserve dtypes
241241
expected = expected.astype("float64")
242242

@@ -273,7 +273,7 @@ def test_transform_groupby_kernel_frame(request, axis, float_frame, op):
273273
# GH 35964
274274

275275
args = [0.0] if op == "fillna" else []
276-
if axis == 0 or axis == "index":
276+
if axis in (0, "index"):
277277
ones = np.ones(float_frame.shape[0])
278278
else:
279279
ones = np.ones(float_frame.shape[1])
@@ -286,7 +286,7 @@ def test_transform_groupby_kernel_frame(request, axis, float_frame, op):
286286
float_frame["E"] = float_frame["A"].copy()
287287
assert len(float_frame._mgr.arrays) > 1
288288

289-
if axis == 0 or axis == "index":
289+
if axis in (0, "index"):
290290
ones = np.ones(float_frame.shape[0])
291291
else:
292292
ones = np.ones(float_frame.shape[1])

pandas/tests/frame/methods/test_interpolate.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ def test_interp_string_axis(self, axis_name, axis_number):
383383
@pytest.mark.parametrize("method", ["ffill", "bfill", "pad"])
384384
def test_interp_fillna_methods(self, request, axis, method, using_array_manager):
385385
# GH 12918
386-
if using_array_manager and (axis == 1 or axis == "columns"):
386+
if using_array_manager and axis in (1, "columns"):
387387
# TODO(ArrayManager) support axis=1
388388
td.mark_array_manager_not_yet_implemented(request)
389389

pandas/tests/indexes/test_setops.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def test_union_different_types(index_flat, index_flat2, request):
103103
# complex objects non-sortable
104104
warn = RuntimeWarning
105105

106-
any_uint64 = idx1.dtype == np.uint64 or idx2.dtype == np.uint64
106+
any_uint64 = np.uint64 in (idx1.dtype, idx2.dtype)
107107
idx1_signed = is_signed_integer_dtype(idx1.dtype)
108108
idx2_signed = is_signed_integer_dtype(idx2.dtype)
109109

pandas/tests/indexing/multiindex/test_slice.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def test_per_axis_per_level_getitem(self):
3535
d,
3636
)
3737
for a, b, c, d in df.index.values
38-
if (a == "A1" or a == "A2" or a == "A3") and (c == "C1" or c == "C3")
38+
if a in ("A1", "A2", "A3") and c in ("C1", "C3")
3939
]
4040
]
4141
tm.assert_frame_equal(result, expected)
@@ -49,8 +49,7 @@ def test_per_axis_per_level_getitem(self):
4949
d,
5050
)
5151
for a, b, c, d in df.index.values
52-
if (a == "A1" or a == "A2" or a == "A3")
53-
and (c == "C1" or c == "C2" or c == "C3")
52+
if a in ("A1", "A2", "A3") and c in ("C1", "C2", "C3")
5453
]
5554
]
5655
result = df.loc[(slice("A1", "A3"), slice(None), slice("C1", "C3")), :]
@@ -121,7 +120,7 @@ def test_per_axis_per_level_getitem(self):
121120
d,
122121
)
123122
for a, b, c, d in s.index.values
124-
if (a == "A1" or a == "A2" or a == "A3") and (c == "C1" or c == "C3")
123+
if a in ("A1", "A2", "A3") and c in ("C1", "C3")
125124
]
126125
]
127126
tm.assert_series_equal(result, expected)
@@ -416,7 +415,7 @@ def test_per_axis_per_level_doc_examples(self):
416415
d,
417416
)
418417
for a, b, c, d in df.index.values
419-
if (a == "A1" or a == "A2" or a == "A3") and (c == "C1" or c == "C3")
418+
if a in ("A1", "A2", "A3") and c in ("C1", "C3")
420419
]
421420
]
422421
tm.assert_frame_equal(result, expected)
@@ -433,7 +432,7 @@ def test_per_axis_per_level_doc_examples(self):
433432
d,
434433
)
435434
for a, b, c, d in df.index.values
436-
if (c == "C1" or c == "C3")
435+
if c in ("C1", "C3")
437436
]
438437
]
439438
tm.assert_frame_equal(result, expected)
@@ -494,7 +493,7 @@ def test_loc_axis_arguments(self):
494493
d,
495494
)
496495
for a, b, c, d in df.index.values
497-
if (a == "A1" or a == "A2" or a == "A3") and (c == "C1" or c == "C3")
496+
if a in ("A1", "A2", "A3") and c in ("C1", "C3")
498497
]
499498
]
500499
tm.assert_frame_equal(result, expected)
@@ -509,7 +508,7 @@ def test_loc_axis_arguments(self):
509508
d,
510509
)
511510
for a, b, c, d in df.index.values
512-
if (c == "C1" or c == "C3")
511+
if c in ("C1", "C3")
513512
]
514513
]
515514
tm.assert_frame_equal(result, expected)

pandas/tests/io/excel/test_readers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1222,7 +1222,7 @@ def test_read_excel_nrows_non_integer_parameter(self, read_ext):
12221222
("testmultiindex", "both", [0, 1], [0, 1], None),
12231223
("testmultiindex", "mi_column_name", [0, 1], 0, None),
12241224
("testskiprows", "skiprows_list", None, None, [0, 2]),
1225-
("testskiprows", "skiprows_list", None, None, lambda x: x == 0 or x == 2),
1225+
("testskiprows", "skiprows_list", None, None, lambda x: x in (0, 2)),
12261226
],
12271227
)
12281228
def test_read_excel_nrows_params(

pandas/tests/io/json/test_pandas.py

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

2525

2626
def assert_json_roundtrip_equal(result, expected, orient):
27-
if orient == "records" or orient == "values":
27+
if orient in ("records", "values"):
2828
expected = expected.reset_index(drop=True)
2929
if orient == "values":
3030
expected.columns = range(len(expected.columns))

pandas/tests/util/test_assert_series_equal.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,7 @@ def test_less_precise(data1, data2, dtype, decimals):
115115
s1 = Series([data1], dtype=dtype)
116116
s2 = Series([data2], dtype=dtype)
117117

118-
if (decimals == 5 or decimals == 10) or (
119-
decimals >= 3 and abs(data1 - data2) >= 0.0005
120-
):
118+
if decimals in (5, 10) or (decimals >= 3 and abs(data1 - data2) >= 0.0005):
121119
if is_extension_array_dtype(dtype):
122120
msg = "ExtensionArray are different"
123121
else:

pandas/tseries/frequencies.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -642,7 +642,7 @@ def _is_quarterly(rule: str) -> bool:
642642

643643
def _is_monthly(rule: str) -> bool:
644644
rule = rule.upper()
645-
return rule == "M" or rule == "BM"
645+
return rule in ("M", "BM")
646646

647647

648648
def _is_weekly(rule: str) -> bool:

pandas/tseries/holiday.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,9 @@ def next_monday_or_tuesday(dt: datetime) -> datetime:
5454
(because Monday is already taken by adjacent holiday on the day before)
5555
"""
5656
dow = dt.weekday()
57-
if dow == 5 or dow == 6:
57+
if dow in (5, 6):
5858
return dt + timedelta(2)
59-
elif dow == 0:
59+
if dow == 0:
6060
return dt + timedelta(1)
6161
return dt
6262

0 commit comments

Comments
 (0)