Skip to content

Commit 667418e

Browse files
tqa236pmhatre1
authored andcommitted
Autofix ruf010 (pandas-dev#56914)
* STY: Autofix RUF010 * STY: Apply ruff format after autofix * STY: Final manual fix * STY: Remove old repl rule in pre-commit
1 parent 019c337 commit 667418e

Some content is hidden

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

52 files changed

+114
-128
lines changed

.pre-commit-config.yaml

-3
Original file line numberDiff line numberDiff line change
@@ -190,9 +190,6 @@ repos:
190190
# Check for deprecated messages without sphinx directive
191191
|(DEPRECATED|DEPRECATE|Deprecated)(:|,|\.)
192192
193-
# {foo!r} instead of {repr(foo)}
194-
|!r}
195-
196193
# builtin filter function
197194
|(?<!def)[\(\s]filter\(
198195
types_or: [python, cython, rst]

doc/scripts/eval_performance.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def bench_with(n, times=10, repeat=3, engine="numexpr"):
1717
return (
1818
np.array(
1919
timeit(
20-
f"df.eval(s, engine={repr(engine)})",
20+
f"df.eval(s, engine={engine!r})",
2121
setup=setup_common % (n, setup_with),
2222
repeat=repeat,
2323
number=times,
@@ -34,7 +34,7 @@ def bench_subset(n, times=20, repeat=3, engine="numexpr"):
3434
return (
3535
np.array(
3636
timeit(
37-
f"df.query(s, engine={repr(engine)})",
37+
f"df.query(s, engine={engine!r})",
3838
setup=setup_common % (n, setup_subset),
3939
repeat=repeat,
4040
number=times,
@@ -55,7 +55,7 @@ def bench(mn=3, mx=7, num=100, engines=("python", "numexpr"), verbose=False):
5555
for engine in engines:
5656
for i, n in enumerate(r):
5757
if verbose & (i % 10 == 0):
58-
print(f"engine: {repr(engine)}, i == {i:d}")
58+
print(f"engine: {engine!r}, i == {i:d}")
5959
ev_times = bench_with(n, times=1, repeat=1, engine=engine)
6060
ev.loc[i, engine] = np.mean(ev_times)
6161
qu_times = bench_subset(n, times=1, repeat=1, engine=engine)

pandas/_config/config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ def _get_single_key(pat: str, silent: bool) -> str:
130130
if len(keys) == 0:
131131
if not silent:
132132
_warn_if_deprecated(pat)
133-
raise OptionError(f"No such keys(s): {repr(pat)}")
133+
raise OptionError(f"No such keys(s): {pat!r}")
134134
if len(keys) > 1:
135135
raise OptionError("Pattern matched multiple keys")
136136
key = keys[0]

pandas/_testing/_warnings.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -152,13 +152,12 @@ def _assert_caught_expected_warning(
152152

153153
if not saw_warning:
154154
raise AssertionError(
155-
f"Did not see expected warning of class "
156-
f"{repr(expected_warning.__name__)}"
155+
f"Did not see expected warning of class {expected_warning.__name__!r}"
157156
)
158157

159158
if match and not matched_message:
160159
raise AssertionError(
161-
f"Did not see warning {repr(expected_warning.__name__)} "
160+
f"Did not see warning {expected_warning.__name__!r} "
162161
f"matching '{match}'. The emitted warning messages are "
163162
f"{unmatched_messages}"
164163
)
@@ -200,7 +199,7 @@ def _assert_caught_no_extra_warnings(
200199
)
201200

202201
if extra_warnings:
203-
raise AssertionError(f"Caused unexpected warning(s): {repr(extra_warnings)}")
202+
raise AssertionError(f"Caused unexpected warning(s): {extra_warnings!r}")
204203

205204

206205
def _is_unexpected_warning(

pandas/_testing/asserters.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -432,14 +432,14 @@ def assert_is_valid_plot_return_object(objs) -> None:
432432
for el in objs.ravel():
433433
msg = (
434434
"one of 'objs' is not a matplotlib Axes instance, "
435-
f"type encountered {repr(type(el).__name__)}"
435+
f"type encountered {type(el).__name__!r}"
436436
)
437437
assert isinstance(el, (Axes, dict)), msg
438438
else:
439439
msg = (
440440
"objs is neither an ndarray of Artist instances nor a single "
441441
"ArtistArtist instance, tuple, or dict, 'objs' is a "
442-
f"{repr(type(objs).__name__)}"
442+
f"{type(objs).__name__!r}"
443443
)
444444
assert isinstance(objs, (Artist, tuple, dict)), msg
445445

@@ -661,10 +661,10 @@ def _get_base(obj):
661661

662662
if check_same == "same":
663663
if left_base is not right_base:
664-
raise AssertionError(f"{repr(left_base)} is not {repr(right_base)}")
664+
raise AssertionError(f"{left_base!r} is not {right_base!r}")
665665
elif check_same == "copy":
666666
if left_base is right_base:
667-
raise AssertionError(f"{repr(left_base)} is {repr(right_base)}")
667+
raise AssertionError(f"{left_base!r} is {right_base!r}")
668668

669669
def _raise(left, right, err_msg) -> NoReturn:
670670
if err_msg is None:
@@ -935,7 +935,7 @@ def assert_series_equal(
935935
raise_assert_detail(obj, "Series length are different", msg1, msg2)
936936

937937
if check_flags:
938-
assert left.flags == right.flags, f"{repr(left.flags)} != {repr(right.flags)}"
938+
assert left.flags == right.flags, f"{left.flags!r} != {right.flags!r}"
939939

940940
if check_index:
941941
# GH #38183
@@ -1215,11 +1215,11 @@ def assert_frame_equal(
12151215
# shape comparison
12161216
if left.shape != right.shape:
12171217
raise_assert_detail(
1218-
obj, f"{obj} shape mismatch", f"{repr(left.shape)}", f"{repr(right.shape)}"
1218+
obj, f"{obj} shape mismatch", f"{left.shape!r}", f"{right.shape!r}"
12191219
)
12201220

12211221
if check_flags:
1222-
assert left.flags == right.flags, f"{repr(left.flags)} != {repr(right.flags)}"
1222+
assert left.flags == right.flags, f"{left.flags!r} != {right.flags!r}"
12231223

12241224
# index comparison
12251225
assert_index_equal(
@@ -1369,7 +1369,7 @@ def assert_sp_array_equal(left, right) -> None:
13691369

13701370
def assert_contains_all(iterable, dic) -> None:
13711371
for k in iterable:
1372-
assert k in dic, f"Did not contain item: {repr(k)}"
1372+
assert k in dic, f"Did not contain item: {k!r}"
13731373

13741374

13751375
def assert_copy(iter1, iter2, **eql_kwargs) -> None:
@@ -1384,7 +1384,7 @@ def assert_copy(iter1, iter2, **eql_kwargs) -> None:
13841384
for elem1, elem2 in zip(iter1, iter2):
13851385
assert_almost_equal(elem1, elem2, **eql_kwargs)
13861386
msg = (
1387-
f"Expected object {repr(type(elem1))} and object {repr(type(elem2))} to be "
1387+
f"Expected object {type(elem1)!r} and object {type(elem2)!r} to be "
13881388
"different objects, but they were the same object."
13891389
)
13901390
assert elem1 is not elem2, msg

pandas/_version.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
141141

142142
if verbose:
143143
print(
144-
f"Tried directories {str(rootdirs)} \
144+
f"Tried directories {rootdirs!s} \
145145
but none started with prefix {parentdir_prefix}"
146146
)
147147
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")

pandas/conftest.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ def configure_tests() -> None:
273273
# ----------------------------------------------------------------
274274
# Common arguments
275275
# ----------------------------------------------------------------
276-
@pytest.fixture(params=[0, 1, "index", "columns"], ids=lambda x: f"axis={repr(x)}")
276+
@pytest.fixture(params=[0, 1, "index", "columns"], ids=lambda x: f"axis={x!r}")
277277
def axis(request):
278278
"""
279279
Fixture for returning the axis numbers of a DataFrame.

pandas/core/accessor.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -306,8 +306,8 @@ def plot(self):
306306
def decorator(accessor):
307307
if hasattr(cls, name):
308308
warnings.warn(
309-
f"registration of accessor {repr(accessor)} under name "
310-
f"{repr(name)} for type {repr(cls)} is overriding a preexisting "
309+
f"registration of accessor {accessor!r} under name "
310+
f"{name!r} for type {cls!r} is overriding a preexisting "
311311
f"attribute with the same name.",
312312
UserWarning,
313313
stacklevel=find_stack_level(),

pandas/core/array_algos/replace.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def _check_comparison_types(
7878
type_names[0] = f"ndarray(dtype={a.dtype})"
7979

8080
raise TypeError(
81-
f"Cannot compare types {repr(type_names[0])} and {repr(type_names[1])}"
81+
f"Cannot compare types {type_names[0]!r} and {type_names[1]!r}"
8282
)
8383

8484
if not regex or not should_use_regex(regex, b):

pandas/core/arrays/arrow/array.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1109,7 +1109,7 @@ def fillna(
11091109
try:
11101110
fill_value = self._box_pa(value, pa_type=self._pa_array.type)
11111111
except pa.ArrowTypeError as err:
1112-
msg = f"Invalid value '{str(value)}' for dtype {self.dtype}"
1112+
msg = f"Invalid value '{value!s}' for dtype {self.dtype}"
11131113
raise TypeError(msg) from err
11141114

11151115
try:
@@ -2065,7 +2065,7 @@ def _maybe_convert_setitem_value(self, value):
20652065
try:
20662066
value = self._box_pa(value, self._pa_array.type)
20672067
except pa.ArrowTypeError as err:
2068-
msg = f"Invalid value '{str(value)}' for dtype {self.dtype}"
2068+
msg = f"Invalid value '{value!s}' for dtype {self.dtype}"
20692069
raise TypeError(msg) from err
20702070
return value
20712071

pandas/core/arrays/categorical.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2024,7 +2024,7 @@ def sort_values(
20242024
"""
20252025
inplace = validate_bool_kwarg(inplace, "inplace")
20262026
if na_position not in ["last", "first"]:
2027-
raise ValueError(f"invalid na_position: {repr(na_position)}")
2027+
raise ValueError(f"invalid na_position: {na_position!r}")
20282028

20292029
sorted_idx = nargsort(self, ascending=ascending, na_position=na_position)
20302030

pandas/core/arrays/masked.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ def _validate_setitem_value(self, value):
303303

304304
# Note: without the "str" here, the f-string rendering raises in
305305
# py38 builds.
306-
raise TypeError(f"Invalid value '{str(value)}' for dtype {self.dtype}")
306+
raise TypeError(f"Invalid value '{value!s}' for dtype {self.dtype}")
307307

308308
def __setitem__(self, key, value) -> None:
309309
key = check_array_indexer(self, key)

pandas/core/computation/align.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def _align_core(terms):
127127
if ordm >= 1 and reindexer_size >= 10000:
128128
w = (
129129
f"Alignment difference on axis {axis} is larger "
130-
f"than an order of magnitude on term {repr(terms[i].name)}, "
130+
f"than an order of magnitude on term {terms[i].name!r}, "
131131
f"by more than {ordm:.4g}; performance may suffer."
132132
)
133133
warnings.warn(

pandas/core/computation/expressions.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -214,9 +214,9 @@ def _bool_arith_fallback(op_str, a, b) -> bool:
214214
if _has_bool_dtype(a) and _has_bool_dtype(b):
215215
if op_str in _BOOL_OP_UNSUPPORTED:
216216
warnings.warn(
217-
f"evaluating in Python space because the {repr(op_str)} "
217+
f"evaluating in Python space because the {op_str!r} "
218218
"operator is not supported by numexpr for the bool dtype, "
219-
f"use {repr(_BOOL_OP_UNSUPPORTED[op_str])} instead.",
219+
f"use {_BOOL_OP_UNSUPPORTED[op_str]!r} instead.",
220220
stacklevel=find_stack_level(),
221221
)
222222
return True

pandas/core/computation/ops.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def type(self):
160160

161161
@property
162162
def raw(self) -> str:
163-
return f"{type(self).__name__}(name={repr(self.name)}, type={self.type})"
163+
return f"{type(self).__name__}(name={self.name!r}, type={self.type})"
164164

165165
@property
166166
def is_datetime(self) -> bool:
@@ -387,7 +387,7 @@ def __init__(self, op: str, lhs, rhs) -> None:
387387
# has to be made a list for python3
388388
keys = list(_binary_ops_dict.keys())
389389
raise ValueError(
390-
f"Invalid binary operator {repr(op)}, valid operators are {keys}"
390+
f"Invalid binary operator {op!r}, valid operators are {keys}"
391391
) from err
392392

393393
def __call__(self, env):
@@ -571,7 +571,7 @@ def __init__(self, op: Literal["+", "-", "~", "not"], operand) -> None:
571571
self.func = _unary_ops_dict[op]
572572
except KeyError as err:
573573
raise ValueError(
574-
f"Invalid unary operator {repr(op)}, "
574+
f"Invalid unary operator {op!r}, "
575575
f"valid operators are {UNARY_OPS_SYMS}"
576576
) from err
577577

pandas/core/computation/pytables.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def _resolve_name(self):
8181
if self.side == "left":
8282
# Note: The behavior of __new__ ensures that self.name is a str here
8383
if self.name not in self.env.queryables:
84-
raise NameError(f"name {repr(self.name)} is not defined")
84+
raise NameError(f"name {self.name!r} is not defined")
8585
return self.name
8686

8787
# resolve the rhs (and allow it to be None)
@@ -467,9 +467,7 @@ def visit_Subscript(self, node, **kwargs) -> ops.Term:
467467
try:
468468
return self.const_type(value[slobj], self.env)
469469
except TypeError as err:
470-
raise ValueError(
471-
f"cannot subscript {repr(value)} with {repr(slobj)}"
472-
) from err
470+
raise ValueError(f"cannot subscript {value!r} with {slobj!r}") from err
473471

474472
def visit_Attribute(self, node, **kwargs):
475473
attr = node.attr

pandas/core/dtypes/cast.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ def _disallow_mismatched_datetimelike(value, dtype: DtypeObj) -> None:
243243
elif (vdtype.kind == "m" and dtype.kind == "M") or (
244244
vdtype.kind == "M" and dtype.kind == "m"
245245
):
246-
raise TypeError(f"Cannot cast {repr(value)} to {dtype}")
246+
raise TypeError(f"Cannot cast {value!r} to {dtype}")
247247

248248

249249
@overload

pandas/core/dtypes/common.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1548,8 +1548,8 @@ def _validate_date_like_dtype(dtype) -> None:
15481548
raise TypeError(e) from e
15491549
if typ not in ["generic", "ns"]:
15501550
raise ValueError(
1551-
f"{repr(dtype.name)} is too specific of a frequency, "
1552-
f"try passing {repr(dtype.type.__name__)}"
1551+
f"{dtype.name!r} is too specific of a frequency, "
1552+
f"try passing {dtype.type.__name__!r}"
15531553
)
15541554

15551555

pandas/core/dtypes/dtypes.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ def _from_values_or_dtype(
318318

319319
dtype = CategoricalDtype(categories, ordered)
320320
else:
321-
raise ValueError(f"Unknown dtype {repr(dtype)}")
321+
raise ValueError(f"Unknown dtype {dtype!r}")
322322
elif categories is not None or ordered is not None:
323323
raise ValueError(
324324
"Cannot specify `categories` or `ordered` together with `dtype`."
@@ -566,7 +566,7 @@ def validate_categories(categories, fastpath: bool = False) -> Index:
566566

567567
if not fastpath and not is_list_like(categories):
568568
raise TypeError(
569-
f"Parameter 'categories' must be list-like, was {repr(categories)}"
569+
f"Parameter 'categories' must be list-like, was {categories!r}"
570570
)
571571
if not isinstance(categories, ABCIndex):
572572
categories = Index._with_infer(categories, tupleize_cols=False)
@@ -602,7 +602,7 @@ def update_dtype(self, dtype: str_type | CategoricalDtype) -> CategoricalDtype:
602602
elif not self.is_dtype(dtype):
603603
raise ValueError(
604604
f"a CategoricalDtype must be passed to perform an update, "
605-
f"got {repr(dtype)}"
605+
f"got {dtype!r}"
606606
)
607607
else:
608608
# from here on, dtype is a CategoricalDtype
@@ -1458,7 +1458,7 @@ def __init__(self, dtype: npt.DTypeLike | NumpyEADtype | None) -> None:
14581458
self._dtype = np.dtype(dtype)
14591459

14601460
def __repr__(self) -> str:
1461-
return f"NumpyEADtype({repr(self.name)})"
1461+
return f"NumpyEADtype({self.name!r})"
14621462

14631463
@property
14641464
def numpy_dtype(self) -> np.dtype:
@@ -1814,7 +1814,7 @@ def subtype(self):
18141814

18151815
@property
18161816
def name(self) -> str:
1817-
return f"Sparse[{self.subtype.name}, {repr(self.fill_value)}]"
1817+
return f"Sparse[{self.subtype.name}, {self.fill_value!r}]"
18181818

18191819
def __repr__(self) -> str:
18201820
return self.name
@@ -2173,7 +2173,7 @@ def name(self) -> str: # type: ignore[override]
21732173
"""
21742174
A string identifying the data type.
21752175
"""
2176-
return f"{str(self.pyarrow_dtype)}[{self.storage}]"
2176+
return f"{self.pyarrow_dtype!s}[{self.storage}]"
21772177

21782178
@cache_readonly
21792179
def numpy_dtype(self) -> np.dtype:

pandas/core/frame.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -10395,9 +10395,7 @@ def map(
1039510395
1 11.262736 20.857489
1039610396
"""
1039710397
if na_action not in {"ignore", None}:
10398-
raise ValueError(
10399-
f"na_action must be 'ignore' or None. Got {repr(na_action)}"
10400-
)
10398+
raise ValueError(f"na_action must be 'ignore' or None. Got {na_action!r}")
1040110399

1040210400
if self.empty:
1040310401
return self.copy()
@@ -11860,7 +11858,7 @@ def _get_agg_axis(self, axis_num: int) -> Index:
1186011858
elif axis_num == 1:
1186111859
return self.index
1186211860
else:
11863-
raise ValueError(f"Axis must be 0 or 1 (got {repr(axis_num)})")
11861+
raise ValueError(f"Axis must be 0 or 1 (got {axis_num!r})")
1186411862

1186511863
def mode(
1186611864
self, axis: Axis = 0, numeric_only: bool = False, dropna: bool = True

0 commit comments

Comments
 (0)