Skip to content

Commit 8fac6fd

Browse files
committed
add f-strings to indexes.base.py
1 parent d36bc70 commit 8fac6fd

File tree

1 file changed

+28
-38
lines changed

1 file changed

+28
-38
lines changed

pandas/core/indexes/base.py

+28-38
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

@@ -768,8 +768,7 @@ def astype(self, dtype, copy=True):
768768
self.values.astype(dtype, copy=copy), name=self.name, dtype=dtype
769769
)
770770
except (TypeError, ValueError):
771-
msg = "Cannot cast {name} to dtype {dtype}"
772-
raise TypeError(msg.format(name=type(self).__name__, dtype=dtype))
771+
raise TypeError(f"Cannot cast {type(self).__name__} to dtype {dtype}")
773772

774773
_index_shared_docs[
775774
"take"
@@ -814,8 +813,9 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):
814813
)
815814
else:
816815
if allow_fill and fill_value is not None:
817-
msg = "Unable to fill values because {0} cannot contain NA"
818-
raise ValueError(msg.format(self.__class__.__name__))
816+
cls_name = self.__class__.__name__
817+
raise ValueError(
818+
f"Unable to fill values because {cls_name} cannot contain NA")
819819
taken = self.values.take(indices)
820820
return self._shallow_copy(taken)
821821

@@ -1287,8 +1287,7 @@ def _set_names(self, values, level=None):
12871287
for name in values:
12881288
if not is_hashable(name):
12891289
raise TypeError(
1290-
"{}.name must be a hashable type".format(self.__class__.__name__)
1291-
)
1290+
f"{self.__class__.__name__}.name must be a hashable type")
12921291
self.name = values[0]
12931292

12941293
names = property(fset=_set_names, fget=_get_names)
@@ -1456,14 +1455,12 @@ def _validate_index_level(self, level):
14561455
)
14571456
elif level > 0:
14581457
raise IndexError(
1459-
"Too many levels: Index has only 1 level, not %d" % (level + 1)
1458+
f"Too many levels: Index has only 1 level, not {level + 1}"
14601459
)
14611460
elif level != self.name:
14621461
raise KeyError(
1463-
"Requested level ({}) does not match index name ({})".format(
1464-
level, self.name
1462+
f"Requested level ({level}) does not match index name ({self.name})"
14651463
)
1466-
)
14671464

14681465
def _get_level_number(self, level):
14691466
self._validate_index_level(level)
@@ -1558,9 +1555,8 @@ def droplevel(self, level=0):
15581555
return self
15591556
if len(level) >= self.nlevels:
15601557
raise ValueError(
1561-
"Cannot remove {} levels from an index with {} "
1562-
"levels: at least one level must be "
1563-
"left.".format(len(level), self.nlevels)
1558+
f"Cannot remove {len(level)} levels from an index with {self.nlevels} "
1559+
"levels: at least one level must be left."
15641560
)
15651561
# The two checks above guarantee that here self is a MultiIndex
15661562

@@ -2014,7 +2010,7 @@ def fillna(self, value=None, downcast=None):
20142010
@Appender(_index_shared_docs["dropna"])
20152011
def dropna(self, how="any"):
20162012
if how not in ("any", "all"):
2017-
raise ValueError("invalid how option: {0}".format(how))
2013+
raise ValueError(f"invalid how option: {how}")
20182014

20192015
if self.hasnans:
20202016
return self._shallow_copy(self.values[~self._isnan])
@@ -2288,10 +2284,8 @@ def __xor__(self, other):
22882284

22892285
def __nonzero__(self):
22902286
raise ValueError(
2291-
"The truth value of a {0} is ambiguous. "
2292-
"Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(
2293-
self.__class__.__name__
2294-
)
2287+
f"The truth value of a {self.__class__.__name__} is ambiguous. "
2288+
"Use a.empty, a.bool(), a.item(), a.any() or a.all()."
22952289
)
22962290

22972291
__bool__ = __nonzero__
@@ -2354,7 +2348,7 @@ def _validate_sort_keyword(self, sort):
23542348
if sort not in [None, False]:
23552349
raise ValueError(
23562350
"The 'sort' keyword only takes the values of "
2357-
"None or False; {0} was passed.".format(sort)
2351+
f"None or False; {sort} was passed."
23582352
)
23592353

23602354
def union(self, other, sort=None):
@@ -2481,10 +2475,9 @@ def _union(self, other, sort):
24812475
if sort is None:
24822476
try:
24832477
result = algos.safe_sort(result)
2484-
except TypeError as e:
2478+
except TypeError as err:
24852479
warnings.warn(
2486-
"{}, sort order is undefined for "
2487-
"incomparable objects".format(e),
2480+
f"{err}, sort order is undefined for incomparable objects",
24882481
RuntimeWarning,
24892482
stacklevel=3,
24902483
)
@@ -2939,8 +2932,8 @@ def _get_fill_indexer_searchsorted(self, target, method, limit=None):
29392932
"""
29402933
if limit is not None:
29412934
raise ValueError(
2942-
"limit argument for %r method only well-defined "
2943-
"if index and target are monotonic" % method
2935+
f"limit argument for {method!r} method only well-defined "
2936+
"if index and target are monotonic"
29442937
)
29452938

29462939
side = "left" if method == "pad" else "right"
@@ -3227,10 +3220,8 @@ def _invalid_indexer(self, form, key):
32273220
Consistent invalid indexer message.
32283221
"""
32293222
raise TypeError(
3230-
"cannot do {form} indexing on {klass} with these "
3231-
"indexers [{key}] of {kind}".format(
3232-
form=form, klass=type(self), key=key, kind=type(key)
3233-
)
3223+
f"cannot do {form} indexing on {type(self)} with these "
3224+
f"indexers [{key}] of {type(key)}"
32343225
)
32353226

32363227
# --------------------------------------------------------------------
@@ -3992,8 +3983,8 @@ def _scalar_data_error(cls, data):
39923983
# We return the TypeError so that we can raise it from the constructor
39933984
# in order to keep mypy happy
39943985
return TypeError(
3995-
"{0}(...) must be called with a collection of some "
3996-
"kind, {1} was passed".format(cls.__name__, repr(data))
3986+
f"{cls.__name__}(...) must be called with a collection of some "
3987+
f"kind, {data!r} was passed"
39973988
)
39983989

39993990
@classmethod
@@ -4037,8 +4028,7 @@ def _assert_can_do_op(self, value):
40374028
Check value is valid for scalar op.
40384029
"""
40394030
if not is_scalar(value):
4040-
msg = "'value' must be a scalar, passed: {0}"
4041-
raise TypeError(msg.format(type(value).__name__))
4031+
raise TypeError(f"'value' must be a scalar, passed: {type(value).__name__}")
40424032

40434033
def _is_memory_usage_qualified(self) -> bool:
40444034
"""
@@ -4113,7 +4103,7 @@ def contains(self, key) -> bool:
41134103
return key in self
41144104

41154105
def __hash__(self):
4116-
raise TypeError("unhashable type: %r" % type(self).__name__)
4106+
raise TypeError(f"unhashable type: {type(self).__name__!r}")
41174107

41184108
def __setitem__(self, key, value):
41194109
raise TypeError("Index does not support mutable operations")
@@ -5052,8 +5042,8 @@ def get_slice_bound(self, label, side, kind):
50525042
slc = lib.maybe_indices_to_slice(slc.astype("i8"), len(self))
50535043
if isinstance(slc, np.ndarray):
50545044
raise KeyError(
5055-
"Cannot get %s slice bound for non-unique "
5056-
"label: %r" % (side, original_label)
5045+
f"Cannot get {side} slice bound for non-unique "
5046+
f"label: {original_label!r}"
50575047
)
50585048

50595049
if isinstance(slc, slice):
@@ -5211,7 +5201,7 @@ def drop(self, labels, errors="raise"):
52115201
mask = indexer == -1
52125202
if mask.any():
52135203
if errors != "ignore":
5214-
raise KeyError("{} not found in axis".format(labels[mask]))
5204+
raise KeyError(f"{labels[mask]} not found in axis")
52155205
indexer = indexer[~mask]
52165206
return self.delete(indexer)
52175207

0 commit comments

Comments
 (0)