Skip to content

Commit d13c9e0

Browse files
fabincacarlotta
and
carlotta
authored
STYLE: fix pylint: no-else-raise (#49520)
* fix pylint: no-else-raise * fix possible imbalanced tuple unpacking warning Co-authored-by: carlotta <[email protected]>
1 parent 62c0fb8 commit d13c9e0

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

65 files changed

+174
-206
lines changed

ci/fix_wheels.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@
44
import zipfile
55

66
try:
7-
_, wheel_path, dest_dir = sys.argv
7+
if len(sys.argv) != 3:
8+
raise ValueError(
9+
"User must pass the path to the wheel and the destination directory."
10+
)
11+
wheel_path = sys.argv[1]
12+
dest_dir = sys.argv[2]
813
# Figure out whether we are building on 32 or 64 bit python
914
is_32 = sys.maxsize <= 2**32
1015
PYTHON_ARCH = "x86" if is_32 else "x64"
@@ -50,5 +55,4 @@
5055
if not success:
5156
os.remove(repaired_wheel_path)
5257
raise exception
53-
else:
54-
print(f"Successfully repaired wheel was written to {repaired_wheel_path}")
58+
print(f"Successfully repaired wheel was written to {repaired_wheel_path}")

doc/make.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -259,8 +259,7 @@ def latex(self, force=False):
259259
"You should check the file "
260260
'"build/latex/pandas.pdf" for problems.'
261261
)
262-
else:
263-
self._run_os("make")
262+
self._run_os("make")
264263
return ret_code
265264

266265
def latex_forced(self):

pandas/_testing/_io.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -243,10 +243,7 @@ def wrapper(*args, **kwargs):
243243

244244
if not isinstance(err, error_classes) or raise_on_error:
245245
raise
246-
else:
247-
pytest.skip(
248-
f"Skipping test due to lack of connectivity and error {err}"
249-
)
246+
pytest.skip(f"Skipping test due to lack of connectivity and error {err}")
250247

251248
return wrapper
252249

pandas/compat/_optional.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,7 @@ def import_optional_dependency(
141141
except ImportError:
142142
if errors == "raise":
143143
raise ImportError(msg)
144-
else:
145-
return None
144+
return None
146145

147146
# Handle submodules: if we have submodule, grab parent module from sys.modules
148147
parent = name.split(".")[0]

pandas/compat/numpy/function.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -412,8 +412,7 @@ def validate_resampler_func(method: str, args, kwargs) -> None:
412412
"numpy operations are not valid with resample. "
413413
f"Use .resample(...).{method}() instead"
414414
)
415-
else:
416-
raise TypeError("too many arguments passed in")
415+
raise TypeError("too many arguments passed in")
417416

418417

419418
def validate_minmax_axis(axis: AxisInt | None, ndim: int = 1) -> None:

pandas/conftest.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1163,8 +1163,7 @@ def deco(*args):
11631163
raise ValueError(
11641164
f"Could not find file {path} and --strict-data-files is set."
11651165
)
1166-
else:
1167-
pytest.skip(f"Could not find {path}.")
1166+
pytest.skip(f"Could not find {path}.")
11681167
return path
11691168

11701169
return deco

pandas/core/apply.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,7 @@ def apply_str(self) -> DataFrame | Series:
464464
"axis" not in arg_names or f in ("corrwith", "skew")
465465
):
466466
raise ValueError(f"Operation {f} does not support axis=1")
467-
elif "axis" in arg_names:
467+
if "axis" in arg_names:
468468
self.kwargs["axis"] = self.axis
469469
return self._try_aggregate_string_function(obj, f, *self.args, **self.kwargs)
470470

@@ -762,7 +762,7 @@ def apply_broadcast(self, target: DataFrame) -> DataFrame:
762762
# must be a scalar or 1d
763763
if ares > 1:
764764
raise ValueError("too many dims to broadcast")
765-
elif ares == 1:
765+
if ares == 1:
766766

767767
# must match return dim
768768
if result_compare != len(res):
@@ -1179,7 +1179,7 @@ def reconstruct_func(
11791179
"Function names must be unique if there is no new column names "
11801180
"assigned"
11811181
)
1182-
elif func is None:
1182+
if func is None:
11831183
# nicer error message
11841184
raise TypeError("Must provide 'func' or tuples of '(column, aggfunc).")
11851185

pandas/core/arrays/datetimelike.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2263,7 +2263,7 @@ def validate_inferred_freq(
22632263
"values does not conform to passed frequency "
22642264
f"{freq.freqstr}"
22652265
)
2266-
elif freq is None:
2266+
if freq is None:
22672267
freq = inferred_freq
22682268
freq_infer = False
22692269

pandas/core/arrays/datetimes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2361,7 +2361,7 @@ def validate_tz_from_dtype(
23612361
if dtz is not None:
23622362
if tz is not None and not timezones.tz_compare(tz, dtz):
23632363
raise ValueError("cannot supply both a tz and a dtype with a tz")
2364-
elif explicit_tz_none:
2364+
if explicit_tz_none:
23652365
raise ValueError("Cannot pass both a timezone-aware dtype and tz=None")
23662366
tz = dtz
23672367

pandas/core/arrays/interval.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -314,17 +314,17 @@ def _simple_new(
314314
f"right [{type(right).__name__}] types"
315315
)
316316
raise ValueError(msg)
317-
elif is_categorical_dtype(left.dtype) or is_string_dtype(left.dtype):
317+
if is_categorical_dtype(left.dtype) or is_string_dtype(left.dtype):
318318
# GH 19016
319319
msg = (
320320
"category, object, and string subtypes are not supported "
321321
"for IntervalArray"
322322
)
323323
raise TypeError(msg)
324-
elif isinstance(left, ABCPeriodIndex):
324+
if isinstance(left, ABCPeriodIndex):
325325
msg = "Period dtypes are not supported, use a PeriodIndex instead"
326326
raise ValueError(msg)
327-
elif isinstance(left, ABCDatetimeIndex) and str(left.tz) != str(right.tz):
327+
if isinstance(left, ABCDatetimeIndex) and str(left.tz) != str(right.tz):
328328
msg = (
329329
"left and right must have the same time zone, got "
330330
f"'{left.tz}' and '{right.tz}'"
@@ -1321,7 +1321,7 @@ def mid(self) -> Index:
13211321
def overlaps(self, other):
13221322
if isinstance(other, (IntervalArray, ABCIntervalIndex)):
13231323
raise NotImplementedError
1324-
elif not isinstance(other, Interval):
1324+
if not isinstance(other, Interval):
13251325
msg = f"`other` must be Interval-like, got {type(other).__name__}"
13261326
raise TypeError(msg)
13271327

pandas/core/arrays/masked.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -655,7 +655,7 @@ def _arith_method(self, other, op):
655655
raise NotImplementedError(
656656
f"operator '{op_name}' not implemented for bool dtypes"
657657
)
658-
elif op_name in {"mod", "rmod"}:
658+
if op_name in {"mod", "rmod"}:
659659
dtype = "int8"
660660
else:
661661
dtype = "bool"
@@ -1034,7 +1034,7 @@ def _quantile(
10341034
# I think this should be out_mask=self.isna().all(axis=1)
10351035
# but am holding off until we have tests
10361036
raise NotImplementedError
1037-
elif self.isna().all():
1037+
if self.isna().all():
10381038
out_mask = np.ones(res.shape, dtype=bool)
10391039
else:
10401040
out_mask = np.zeros(res.shape, dtype=bool)

pandas/core/arrays/period.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1167,7 +1167,7 @@ def _make_field_arrays(*fields) -> list[np.ndarray]:
11671167
if isinstance(x, (list, np.ndarray, ABCSeries)):
11681168
if length is not None and len(x) != length:
11691169
raise ValueError("Mismatched Period array lengths")
1170-
elif length is None:
1170+
if length is None:
11711171
length = len(x)
11721172

11731173
# error: Argument 2 to "repeat" has incompatible type "Optional[int]"; expected

pandas/core/arrays/sparse/array.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -781,7 +781,7 @@ def fillna(
781781
):
782782
raise ValueError("Must specify one of 'method' or 'value'.")
783783

784-
elif method is not None:
784+
if method is not None:
785785
msg = "fillna with 'method' requires high memory usage."
786786
warnings.warn(
787787
msg,
@@ -1172,8 +1172,7 @@ def _take_without_fill(self: SparseArrayT, indices) -> SparseArrayT:
11721172
if (indices.max() >= n) or (indices.min() < -n):
11731173
if n == 0:
11741174
raise IndexError("cannot do a non-empty take from an empty axes.")
1175-
else:
1176-
raise IndexError("out of bounds value in 'indices'.")
1175+
raise IndexError("out of bounds value in 'indices'.")
11771176

11781177
if to_shift.any():
11791178
indices = indices.copy()

pandas/core/arrays/timedeltas.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -490,7 +490,7 @@ def __truediv__(self, other):
490490
if len(other) != len(self):
491491
raise ValueError("Cannot divide vectors with unequal lengths")
492492

493-
elif is_timedelta64_dtype(other.dtype):
493+
if is_timedelta64_dtype(other.dtype):
494494
# let numpy handle it
495495
return self._ndarray / other
496496

@@ -554,7 +554,7 @@ def __rtruediv__(self, other):
554554
if len(other) != len(self):
555555
raise ValueError("Cannot divide vectors with unequal lengths")
556556

557-
elif is_timedelta64_dtype(other.dtype):
557+
if is_timedelta64_dtype(other.dtype):
558558
# let numpy handle it
559559
return other / self._ndarray
560560

@@ -606,7 +606,7 @@ def __floordiv__(self, other):
606606
if len(other) != len(self):
607607
raise ValueError("Cannot divide with unequal lengths")
608608

609-
elif is_timedelta64_dtype(other.dtype):
609+
if is_timedelta64_dtype(other.dtype):
610610
other = type(self)(other)
611611

612612
# numpy timedelta64 does not natively support floordiv, so operate
@@ -675,7 +675,7 @@ def __rfloordiv__(self, other):
675675
if len(other) != len(self):
676676
raise ValueError("Cannot divide with unequal lengths")
677677

678-
elif is_timedelta64_dtype(other.dtype):
678+
if is_timedelta64_dtype(other.dtype):
679679
other = type(self)(other)
680680
# numpy timedelta64 does not natively support floordiv, so operate
681681
# on the i8 values

pandas/core/common.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ def standardize_mapping(into):
388388
into = type(into)
389389
if not issubclass(into, abc.Mapping):
390390
raise TypeError(f"unsupported type: {into}")
391-
elif into == defaultdict:
391+
if into == defaultdict:
392392
raise TypeError("to_dict() only accepts initialized defaultdicts")
393393
return into
394394

pandas/core/computation/eval.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,7 @@ def eval(
344344
"Multi-line expressions are only valid "
345345
"if all expressions contain an assignment"
346346
)
347-
elif inplace:
347+
if inplace:
348348
raise ValueError("Cannot operate inplace if there is no assignment")
349349

350350
# assign if needed

pandas/core/construction.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -698,7 +698,7 @@ def _sanitize_ndim(
698698
if getattr(result, "ndim", 0) == 0:
699699
raise ValueError("result should be arraylike with ndim > 0")
700700

701-
elif result.ndim == 1:
701+
if result.ndim == 1:
702702
# the result that we want
703703
result = _maybe_repeat(result, index)
704704

pandas/core/dtypes/cast.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -1866,7 +1866,7 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any:
18661866
return element
18671867
raise LossySetitemError
18681868

1869-
elif is_integer(element) or (is_float(element) and element.is_integer()):
1869+
if is_integer(element) or (is_float(element) and element.is_integer()):
18701870
# e.g. test_setitem_series_int8 if we have a python int 1
18711871
# tipo may be np.int32, despite the fact that it will fit
18721872
# in smaller int dtypes.
@@ -1893,7 +1893,7 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any:
18931893

18941894
# Anything other than integer we cannot hold
18951895
raise LossySetitemError
1896-
elif (
1896+
if (
18971897
dtype.kind == "u"
18981898
and isinstance(element, np.ndarray)
18991899
and element.dtype.kind == "i"
@@ -1905,9 +1905,9 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any:
19051905
# itemsize issues there?
19061906
return casted
19071907
raise LossySetitemError
1908-
elif dtype.itemsize < tipo.itemsize:
1908+
if dtype.itemsize < tipo.itemsize:
19091909
raise LossySetitemError
1910-
elif not isinstance(tipo, np.dtype):
1910+
if not isinstance(tipo, np.dtype):
19111911
# i.e. nullable IntegerDtype; we can put this into an ndarray
19121912
# losslessly iff it has no NAs
19131913
if element._hasna:
@@ -1918,7 +1918,7 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any:
19181918

19191919
raise LossySetitemError
19201920

1921-
elif dtype.kind == "f":
1921+
if dtype.kind == "f":
19221922
if lib.is_integer(element) or lib.is_float(element):
19231923
casted = dtype.type(element)
19241924
if np.isnan(casted) or casted == element:
@@ -1931,7 +1931,7 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any:
19311931
if tipo.kind not in ["f", "i", "u"]:
19321932
# Anything other than float/integer we cannot hold
19331933
raise LossySetitemError
1934-
elif not isinstance(tipo, np.dtype):
1934+
if not isinstance(tipo, np.dtype):
19351935
# i.e. nullable IntegerDtype or FloatingDtype;
19361936
# we can put this into an ndarray losslessly iff it has no NAs
19371937
if element._hasna:
@@ -1950,7 +1950,7 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any:
19501950

19511951
raise LossySetitemError
19521952

1953-
elif dtype.kind == "c":
1953+
if dtype.kind == "c":
19541954
if lib.is_integer(element) or lib.is_complex(element) or lib.is_float(element):
19551955
if np.isnan(element):
19561956
# see test_where_complex GH#6345
@@ -1968,7 +1968,7 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any:
19681968
raise LossySetitemError
19691969
raise LossySetitemError
19701970

1971-
elif dtype.kind == "b":
1971+
if dtype.kind == "b":
19721972
if tipo is not None:
19731973
if tipo.kind == "b":
19741974
if not isinstance(tipo, np.dtype):
@@ -1982,7 +1982,7 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any:
19821982
return element
19831983
raise LossySetitemError
19841984

1985-
elif dtype.kind == "S":
1985+
if dtype.kind == "S":
19861986
# TODO: test tests.frame.methods.test_replace tests get here,
19871987
# need more targeted tests. xref phofl has a PR about this
19881988
if tipo is not None:

pandas/core/dtypes/common.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1471,7 +1471,7 @@ def get_dtype(arr_or_dtype) -> DtypeObj:
14711471
raise TypeError("Cannot deduce dtype from null object")
14721472

14731473
# fastpath
1474-
elif isinstance(arr_or_dtype, np.dtype):
1474+
if isinstance(arr_or_dtype, np.dtype):
14751475
return arr_or_dtype
14761476
elif isinstance(arr_or_dtype, type):
14771477
return np.dtype(arr_or_dtype)
@@ -1639,8 +1639,7 @@ def validate_all_hashable(*args, error_name: str | None = None) -> None:
16391639
if not all(is_hashable(arg) for arg in args):
16401640
if error_name:
16411641
raise TypeError(f"{error_name} must be a hashable type")
1642-
else:
1643-
raise TypeError("All elements must be hashable")
1642+
raise TypeError("All elements must be hashable")
16441643

16451644

16461645
def pandas_dtype(dtype) -> DtypeObj:

pandas/core/dtypes/dtypes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,7 @@ def validate_categories(categories, fastpath: bool = False) -> Index:
523523
raise TypeError(
524524
f"Parameter 'categories' must be list-like, was {repr(categories)}"
525525
)
526-
elif not isinstance(categories, ABCIndex):
526+
if not isinstance(categories, ABCIndex):
527527
categories = Index._with_infer(categories, tupleize_cols=False)
528528

529529
if not fastpath:

0 commit comments

Comments
 (0)