Skip to content

Commit f5c102f

Browse files
topper-123jreback
authored andcommitted
Convert core/indexes/base.py to f-strings (#29903)
1 parent 0624ec9 commit f5c102f

File tree

1 file changed

+30
-40
lines changed

1 file changed

+30
-40
lines changed

pandas/core/indexes/base.py

+30-40
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ def cmp_method(self, other):
120120
return result
121121
return ops.invalid_comparison(self, other, op)
122122

123-
name = "__{name}__".format(name=op.__name__)
123+
name = f"__{op.__name__}__"
124124
return set_function_name(cmp_method, name, cls)
125125

126126

@@ -136,7 +136,7 @@ def index_arithmetic_method(self, other):
136136
return (Index(result[0]), Index(result[1]))
137137
return Index(result)
138138

139-
name = "__{name}__".format(name=op.__name__)
139+
name = f"__{op.__name__}__"
140140
# TODO: docstring?
141141
return set_function_name(index_arithmetic_method, name, cls)
142142

@@ -441,7 +441,7 @@ def __new__(
441441
except IncompatibleFrequency:
442442
pass
443443
if kwargs:
444-
raise TypeError(f"Unexpected keyword arguments {set(kwargs)!r}")
444+
raise TypeError(f"Unexpected keyword arguments {repr(set(kwargs))}")
445445
return cls._simple_new(subarr, name, **kwargs)
446446

447447
elif hasattr(data, "__array__"):
@@ -753,8 +753,7 @@ def astype(self, dtype, copy=True):
753753
self.values.astype(dtype, copy=copy), name=self.name, dtype=dtype
754754
)
755755
except (TypeError, ValueError):
756-
msg = "Cannot cast {name} to dtype {dtype}"
757-
raise TypeError(msg.format(name=type(self).__name__, dtype=dtype))
756+
raise TypeError(f"Cannot cast {type(self).__name__} to dtype {dtype}")
758757

759758
_index_shared_docs[
760759
"take"
@@ -799,8 +798,10 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):
799798
)
800799
else:
801800
if allow_fill and fill_value is not None:
802-
msg = "Unable to fill values because {0} cannot contain NA"
803-
raise ValueError(msg.format(type(self).__name__))
801+
cls_name = type(self).__name__
802+
raise ValueError(
803+
f"Unable to fill values because {cls_name} cannot contain NA"
804+
)
804805
taken = self.values.take(indices)
805806
return self._shallow_copy(taken)
806807

@@ -1271,9 +1272,7 @@ def _set_names(self, values, level=None):
12711272
# All items in 'name' need to be hashable:
12721273
for name in values:
12731274
if not is_hashable(name):
1274-
raise TypeError(
1275-
"{}.name must be a hashable type".format(type(self).__name__)
1276-
)
1275+
raise TypeError(f"{type(self).__name__}.name must be a hashable type")
12771276
self.name = values[0]
12781277

12791278
names = property(fset=_set_names, fget=_get_names)
@@ -1441,13 +1440,11 @@ def _validate_index_level(self, level):
14411440
)
14421441
elif level > 0:
14431442
raise IndexError(
1444-
"Too many levels: Index has only 1 level, not %d" % (level + 1)
1443+
f"Too many levels: Index has only 1 level, not {level + 1}"
14451444
)
14461445
elif level != self.name:
14471446
raise KeyError(
1448-
"Requested level ({}) does not match index name ({})".format(
1449-
level, self.name
1450-
)
1447+
f"Requested level ({level}) does not match index name ({self.name})"
14511448
)
14521449

14531450
def _get_level_number(self, level):
@@ -1543,9 +1540,8 @@ def droplevel(self, level=0):
15431540
return self
15441541
if len(level) >= self.nlevels:
15451542
raise ValueError(
1546-
"Cannot remove {} levels from an index with {} "
1547-
"levels: at least one level must be "
1548-
"left.".format(len(level), self.nlevels)
1543+
f"Cannot remove {len(level)} levels from an index with {self.nlevels} "
1544+
"levels: at least one level must be left."
15491545
)
15501546
# The two checks above guarantee that here self is a MultiIndex
15511547

@@ -1999,7 +1995,7 @@ def fillna(self, value=None, downcast=None):
19991995
@Appender(_index_shared_docs["dropna"])
20001996
def dropna(self, how="any"):
20011997
if how not in ("any", "all"):
2002-
raise ValueError("invalid how option: {0}".format(how))
1998+
raise ValueError(f"invalid how option: {how}")
20031999

20042000
if self.hasnans:
20052001
return self._shallow_copy(self.values[~self._isnan])
@@ -2273,10 +2269,8 @@ def __xor__(self, other):
22732269

22742270
def __nonzero__(self):
22752271
raise ValueError(
2276-
"The truth value of a {0} is ambiguous. "
2277-
"Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(
2278-
type(self).__name__
2279-
)
2272+
f"The truth value of a {type(self).__name__} is ambiguous. "
2273+
"Use a.empty, a.bool(), a.item(), a.any() or a.all()."
22802274
)
22812275

22822276
__bool__ = __nonzero__
@@ -2339,7 +2333,7 @@ def _validate_sort_keyword(self, sort):
23392333
if sort not in [None, False]:
23402334
raise ValueError(
23412335
"The 'sort' keyword only takes the values of "
2342-
"None or False; {0} was passed.".format(sort)
2336+
f"None or False; {sort} was passed."
23432337
)
23442338

23452339
def union(self, other, sort=None):
@@ -2466,10 +2460,9 @@ def _union(self, other, sort):
24662460
if sort is None:
24672461
try:
24682462
result = algos.safe_sort(result)
2469-
except TypeError as e:
2463+
except TypeError as err:
24702464
warnings.warn(
2471-
"{}, sort order is undefined for "
2472-
"incomparable objects".format(e),
2465+
f"{err}, sort order is undefined for incomparable objects",
24732466
RuntimeWarning,
24742467
stacklevel=3,
24752468
)
@@ -2924,8 +2917,8 @@ def _get_fill_indexer_searchsorted(self, target, method, limit=None):
29242917
"""
29252918
if limit is not None:
29262919
raise ValueError(
2927-
"limit argument for %r method only well-defined "
2928-
"if index and target are monotonic" % method
2920+
f"limit argument for {repr(method)} method only well-defined "
2921+
"if index and target are monotonic"
29292922
)
29302923

29312924
side = "left" if method == "pad" else "right"
@@ -3212,10 +3205,8 @@ def _invalid_indexer(self, form, key):
32123205
Consistent invalid indexer message.
32133206
"""
32143207
raise TypeError(
3215-
"cannot do {form} indexing on {klass} with these "
3216-
"indexers [{key}] of {kind}".format(
3217-
form=form, klass=type(self), key=key, kind=type(key)
3218-
)
3208+
f"cannot do {form} indexing on {type(self)} with these "
3209+
f"indexers [{key}] of {type(key)}"
32193210
)
32203211

32213212
# --------------------------------------------------------------------
@@ -3977,8 +3968,8 @@ def _scalar_data_error(cls, data):
39773968
# We return the TypeError so that we can raise it from the constructor
39783969
# in order to keep mypy happy
39793970
return TypeError(
3980-
"{0}(...) must be called with a collection of some "
3981-
"kind, {1} was passed".format(cls.__name__, repr(data))
3971+
f"{cls.__name__}(...) must be called with a collection of some "
3972+
f"kind, {repr(data)} was passed"
39823973
)
39833974

39843975
@classmethod
@@ -4022,8 +4013,7 @@ def _assert_can_do_op(self, value):
40224013
Check value is valid for scalar op.
40234014
"""
40244015
if not is_scalar(value):
4025-
msg = "'value' must be a scalar, passed: {0}"
4026-
raise TypeError(msg.format(type(value).__name__))
4016+
raise TypeError(f"'value' must be a scalar, passed: {type(value).__name__}")
40274017

40284018
def _is_memory_usage_qualified(self) -> bool:
40294019
"""
@@ -4098,7 +4088,7 @@ def contains(self, key) -> bool:
40984088
return key in self
40994089

41004090
def __hash__(self):
4101-
raise TypeError("unhashable type: %r" % type(self).__name__)
4091+
raise TypeError(f"unhashable type: {repr(type(self).__name__)}")
41024092

41034093
def __setitem__(self, key, value):
41044094
raise TypeError("Index does not support mutable operations")
@@ -5037,8 +5027,8 @@ def get_slice_bound(self, label, side, kind):
50375027
slc = lib.maybe_indices_to_slice(slc.astype("i8"), len(self))
50385028
if isinstance(slc, np.ndarray):
50395029
raise KeyError(
5040-
"Cannot get %s slice bound for non-unique "
5041-
"label: %r" % (side, original_label)
5030+
f"Cannot get {side} slice bound for non-unique "
5031+
f"label: {repr(original_label)}"
50425032
)
50435033

50445034
if isinstance(slc, slice):
@@ -5196,7 +5186,7 @@ def drop(self, labels, errors="raise"):
51965186
mask = indexer == -1
51975187
if mask.any():
51985188
if errors != "ignore":
5199-
raise KeyError("{} not found in axis".format(labels[mask]))
5189+
raise KeyError(f"{labels[mask]} not found in axis")
52005190
indexer = indexer[~mask]
52015191
return self.delete(indexer)
52025192

0 commit comments

Comments
 (0)