Skip to content

Commit

Permalink
Convert core/indexes/base.py to f-strings (pandas-dev#29903)
Browse files Browse the repository at this point in the history
  • Loading branch information
topper-123 authored and proost committed Dec 19, 2019
1 parent 28ff696 commit c41c26f
Showing 1 changed file with 30 additions and 40 deletions.
70 changes: 30 additions & 40 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def cmp_method(self, other):
return result
return ops.invalid_comparison(self, other, op)

name = "__{name}__".format(name=op.__name__)
name = f"__{op.__name__}__"
return set_function_name(cmp_method, name, cls)


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

name = "__{name}__".format(name=op.__name__)
name = f"__{op.__name__}__"
# TODO: docstring?
return set_function_name(index_arithmetic_method, name, cls)

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

elif hasattr(data, "__array__"):
Expand Down Expand Up @@ -753,8 +753,7 @@ def astype(self, dtype, copy=True):
self.values.astype(dtype, copy=copy), name=self.name, dtype=dtype
)
except (TypeError, ValueError):
msg = "Cannot cast {name} to dtype {dtype}"
raise TypeError(msg.format(name=type(self).__name__, dtype=dtype))
raise TypeError(f"Cannot cast {type(self).__name__} to dtype {dtype}")

_index_shared_docs[
"take"
Expand Down Expand Up @@ -799,8 +798,10 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):
)
else:
if allow_fill and fill_value is not None:
msg = "Unable to fill values because {0} cannot contain NA"
raise ValueError(msg.format(type(self).__name__))
cls_name = type(self).__name__
raise ValueError(
f"Unable to fill values because {cls_name} cannot contain NA"
)
taken = self.values.take(indices)
return self._shallow_copy(taken)

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

names = property(fset=_set_names, fget=_get_names)
Expand Down Expand Up @@ -1441,13 +1440,11 @@ def _validate_index_level(self, level):
)
elif level > 0:
raise IndexError(
"Too many levels: Index has only 1 level, not %d" % (level + 1)
f"Too many levels: Index has only 1 level, not {level + 1}"
)
elif level != self.name:
raise KeyError(
"Requested level ({}) does not match index name ({})".format(
level, self.name
)
f"Requested level ({level}) does not match index name ({self.name})"
)

def _get_level_number(self, level):
Expand Down Expand Up @@ -1543,9 +1540,8 @@ def droplevel(self, level=0):
return self
if len(level) >= self.nlevels:
raise ValueError(
"Cannot remove {} levels from an index with {} "
"levels: at least one level must be "
"left.".format(len(level), self.nlevels)
f"Cannot remove {len(level)} levels from an index with {self.nlevels} "
"levels: at least one level must be left."
)
# The two checks above guarantee that here self is a MultiIndex

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

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

def __nonzero__(self):
raise ValueError(
"The truth value of a {0} is ambiguous. "
"Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(
type(self).__name__
)
f"The truth value of a {type(self).__name__} is ambiguous. "
"Use a.empty, a.bool(), a.item(), a.any() or a.all()."
)

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

def union(self, other, sort=None):
Expand Down Expand Up @@ -2466,10 +2460,9 @@ def _union(self, other, sort):
if sort is None:
try:
result = algos.safe_sort(result)
except TypeError as e:
except TypeError as err:
warnings.warn(
"{}, sort order is undefined for "
"incomparable objects".format(e),
f"{err}, sort order is undefined for incomparable objects",
RuntimeWarning,
stacklevel=3,
)
Expand Down Expand Up @@ -2924,8 +2917,8 @@ def _get_fill_indexer_searchsorted(self, target, method, limit=None):
"""
if limit is not None:
raise ValueError(
"limit argument for %r method only well-defined "
"if index and target are monotonic" % method
f"limit argument for {repr(method)} method only well-defined "
"if index and target are monotonic"
)

side = "left" if method == "pad" else "right"
Expand Down Expand Up @@ -3212,10 +3205,8 @@ def _invalid_indexer(self, form, key):
Consistent invalid indexer message.
"""
raise TypeError(
"cannot do {form} indexing on {klass} with these "
"indexers [{key}] of {kind}".format(
form=form, klass=type(self), key=key, kind=type(key)
)
f"cannot do {form} indexing on {type(self)} with these "
f"indexers [{key}] of {type(key)}"
)

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

@classmethod
Expand Down Expand Up @@ -4022,8 +4013,7 @@ def _assert_can_do_op(self, value):
Check value is valid for scalar op.
"""
if not is_scalar(value):
msg = "'value' must be a scalar, passed: {0}"
raise TypeError(msg.format(type(value).__name__))
raise TypeError(f"'value' must be a scalar, passed: {type(value).__name__}")

def _is_memory_usage_qualified(self) -> bool:
"""
Expand Down Expand Up @@ -4098,7 +4088,7 @@ def contains(self, key) -> bool:
return key in self

def __hash__(self):
raise TypeError("unhashable type: %r" % type(self).__name__)
raise TypeError(f"unhashable type: {repr(type(self).__name__)}")

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

if isinstance(slc, slice):
Expand Down Expand Up @@ -5196,7 +5186,7 @@ def drop(self, labels, errors="raise"):
mask = indexer == -1
if mask.any():
if errors != "ignore":
raise KeyError("{} not found in axis".format(labels[mask]))
raise KeyError(f"{labels[mask]} not found in axis")
indexer = indexer[~mask]
return self.delete(indexer)

Expand Down

0 comments on commit c41c26f

Please sign in to comment.