Skip to content

CLN: changed .format to f-string in pandas/core/indexes #30273

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions pandas/core/indexes/accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin):
def __init__(self, data, orig):
if not isinstance(data, ABCSeries):
raise TypeError(
"cannot convert an object of type {0} to a "
"datetimelike index".format(type(data))
f"cannot convert an object of type {type(data)} to a "
"datetimelike index"
)

self._parent = data
Expand All @@ -54,8 +54,7 @@ def _get_values(self):
return DatetimeIndex(data, copy=False, name=self.name)

raise TypeError(
"cannot convert an object of type {0} to a "
"datetimelike index".format(type(data))
f"cannot convert an object of type {type(data)} to a datetimelike index"
)

def _delegate_property_get(self, name):
Expand Down Expand Up @@ -315,8 +314,8 @@ def __new__(cls, data):

if not isinstance(data, ABCSeries):
raise TypeError(
"cannot convert an object of type {0} to a "
"datetimelike index".format(type(data))
f"cannot convert an object of type {type(data)} to a "
"datetimelike index"
)

orig = data if is_categorical_dtype(data) else None
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -893,7 +893,7 @@ def _add_comparison_methods(cls):
""" add in comparison methods """

def _make_compare(op):
opname = "__{op}__".format(op=op.__name__)
opname = f"__{op.__name__}__"

def _evaluate_compare(self, other):
with np.errstate(all="ignore"):
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def wrapper(self, other):
return result

wrapper.__doc__ = op.__doc__
wrapper.__name__ = "__{}__".format(op.__name__)
wrapper.__name__ = f"__{op.__name__}__"
return wrapper

@property
Expand Down Expand Up @@ -677,7 +677,7 @@ def _summary(self, name=None):
name = type(self).__name__
result = f"{name}: {len(self)} entries{index_summary}"
if self.freq:
result += "\nFreq: %s" % self.freqstr
result += f"\nFreq: {self.freqstr}"

# display as values, not quoted
result = result.replace("'", "")
Expand Down
16 changes: 6 additions & 10 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,10 +247,8 @@ def __new__(

if is_scalar(data):
raise TypeError(
"{cls}() must be called with a "
"collection of some kind, {data} was passed".format(
cls=cls.__name__, data=repr(data)
)
f"{cls.__name__}() must be called with a "
f"collection of some kind, {repr(data)} was passed"
)

# - Cases checked above all return/raise before reaching here - #
Expand Down Expand Up @@ -973,9 +971,7 @@ def get_loc(self, key, method=None, tolerance=None):
elif isinstance(key, timedelta):
# GH#20464
raise TypeError(
"Cannot index {cls} with {other}".format(
cls=type(self).__name__, other=type(key).__name__
)
f"Cannot index {type(self).__name__} with {type(key).__name__}"
)

if isinstance(key, time):
Expand Down Expand Up @@ -1577,13 +1573,13 @@ def bdate_range(
weekmask = weekmask or "Mon Tue Wed Thu Fri"
freq = prefix_mapping[freq](holidays=holidays, weekmask=weekmask)
except (KeyError, TypeError):
msg = "invalid custom frequency string: {freq}".format(freq=freq)
msg = f"invalid custom frequency string: {freq}"
raise ValueError(msg)
elif holidays or weekmask:
msg = (
"a custom frequency string is required when holidays or "
"weekmask are passed, got frequency {freq}"
).format(freq=freq)
f"weekmask are passed, got frequency {freq}"
)
raise ValueError(msg)

return date_range(
Expand Down
6 changes: 1 addition & 5 deletions pandas/core/indexes/frozen.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,7 @@ def __hash__(self):

def _disabled(self, *args, **kwargs):
"""This method will not function because object is immutable."""
raise TypeError(
"'{cls}' does not support mutable operations.".format(
cls=type(self).__name__
)
)
raise TypeError(f"'{type(self).__name__}' does not support mutable operations.")

def __str__(self) -> str:
return pprint_thing(self, quote_strings=True, escape_chars=("\t", "\r", "\n"))
Expand Down
48 changes: 20 additions & 28 deletions pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,10 @@ def func(intvidx_self, other, sort=False):
common_subtype = find_common_type(subtypes)
if is_object_dtype(common_subtype):
msg = (
"can only do {op} between two IntervalIndex "
f"can only do {self.op_name} between two IntervalIndex "
"objects that have compatible dtypes"
)
raise TypeError(msg.format(op=self.op_name))
raise TypeError(msg)

return setop(intvidx_self, other, sort)

Expand Down Expand Up @@ -432,10 +432,8 @@ def closed(self):
)
def set_closed(self, closed):
if closed not in _VALID_CLOSED:
msg = "invalid option for 'closed': {closed}"
raise ValueError(msg.format(closed=closed))
raise ValueError(f"invalid option for 'closed': {closed}")

# return self._shallow_copy(closed=closed)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason to remove this comment?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. I put it back as it was placed.

array = self._data.set_closed(closed)
return self._simple_new(array, self.name)

Expand Down Expand Up @@ -762,12 +760,12 @@ def _maybe_convert_i8(self, key):

# ensure consistency with IntervalIndex subtype
subtype = self.dtype.subtype
msg = (
"Cannot index an IntervalIndex of subtype {subtype} with "
"values of dtype {other}"
)

if not is_dtype_equal(subtype, key_dtype):
raise ValueError(msg.format(subtype=subtype, other=key_dtype))
raise ValueError(
f"Cannot index an IntervalIndex of subtype {subtype} with "
f"values of dtype {key_dtype}"
)

return key_i8

Expand All @@ -776,8 +774,8 @@ def _check_method(self, method):
return

if method in ["bfill", "backfill", "pad", "ffill", "nearest"]:
msg = "method {method} not yet implemented for IntervalIndex"
raise NotImplementedError(msg.format(method=method))
msg = f"method {method} not yet implemented for IntervalIndex"
raise NotImplementedError(msg)

raise ValueError("Invalid fill method")

Expand Down Expand Up @@ -1165,36 +1163,34 @@ def _format_data(self, name=None):
summary = "[]"
elif n == 1:
first = formatter(self[0])
summary = "[{first}]".format(first=first)
summary = f"[{first}]"
elif n == 2:
first = formatter(self[0])
last = formatter(self[-1])
summary = "[{first}, {last}]".format(first=first, last=last)
summary = f"[{first}, {last}]"
else:

if n > max_seq_items:
n = min(max_seq_items // 2, 10)
head = [formatter(x) for x in self[:n]]
tail = [formatter(x) for x in self[-n:]]
summary = "[{head} ... {tail}]".format(
head=", ".join(head), tail=", ".join(tail)
)
summary = f"[{', '.join(head)} ... {', '.join(tail)}]"
else:
tail = [formatter(x) for x in self]
summary = "[{tail}]".format(tail=", ".join(tail))
summary = f"[{', '.join(tail)}]"

return summary + "," + self._format_space()

def _format_attrs(self):
attrs = [("closed", repr(self.closed))]
if self.name is not None:
attrs.append(("name", default_pprint(self.name)))
attrs.append(("dtype", "'{dtype}'".format(dtype=self.dtype)))
attrs.append(("dtype", f"'{self.dtype}'"))
return attrs

def _format_space(self):
space = " " * (len(type(self).__name__) + 1)
return "\n{space}".format(space=space)
return f"\n{space}"

# --------------------------------------------------------------------

Expand Down Expand Up @@ -1490,25 +1486,21 @@ def interval_range(
)

if not _is_valid_endpoint(start):
msg = "start must be numeric or datetime-like, got {start}"
raise ValueError(msg.format(start=start))
raise ValueError(f"start must be numeric or datetime-like, got {start}")
elif not _is_valid_endpoint(end):
msg = "end must be numeric or datetime-like, got {end}"
raise ValueError(msg.format(end=end))
raise ValueError(f"end must be numeric or datetime-like, got {end}")

if is_float(periods):
periods = int(periods)
elif not is_integer(periods) and periods is not None:
msg = "periods must be a number, got {periods}"
raise TypeError(msg.format(periods=periods))
raise TypeError(f"periods must be a number, got {periods}")

if freq is not None and not is_number(freq):
try:
freq = to_offset(freq)
except ValueError:
raise ValueError(
"freq must be numeric or convertible to "
"DateOffset, got {freq}".format(freq=freq)
f"freq must be numeric or convertible to DateOffset, got {freq}"
)

# verify type compatibility
Expand Down
57 changes: 23 additions & 34 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,35 +343,26 @@ def _verify_integrity(self, codes=None, levels=None):
for i, (level, level_codes) in enumerate(zip(levels, codes)):
if len(level_codes) != codes_length:
raise ValueError(
"Unequal code lengths: %s" % ([len(code_) for code_ in codes])
f"Unequal code lengths: {[len(code_) for code_ in codes]}"
)
if len(level_codes) and level_codes.max() >= len(level):
msg = (
"On level {level}, code max ({max_code}) >= length of "
"level ({level_len}). NOTE: this index is in an "
"inconsistent state".format(
level=i, max_code=level_codes.max(), level_len=len(level)
)
)
raise ValueError(msg)
if len(level_codes) and level_codes.min() < -1:
raise ValueError(
"On level {level}, code value ({code})"
" < -1".format(level=i, code=level_codes.min())
f"On level {i}, code max ({level_codes.max()}) >= length of "
f"level ({len(level)}). NOTE: this index is in an "
"inconsistent state"
)
if len(level_codes) and level_codes.min() < -1:
raise ValueError(f"On level {i}, code value ({level_codes.min()}) < -1")
if not level.is_unique:
raise ValueError(
"Level values must be unique: {values} on "
"level {level}".format(values=list(level), level=i)
f"Level values must be unique: {list(level)} on level {i}"
)
if self.sortorder is not None:
if self.sortorder > self._lexsort_depth():
raise ValueError(
"Value for sortorder must be inferior or equal "
"to actual lexsort_depth: "
"sortorder {sortorder} with lexsort_depth {lexsort_depth}".format(
sortorder=self.sortorder, lexsort_depth=self._lexsort_depth()
)
"Value for sortorder must be inferior or equal to actual "
f"lexsort_depth: sortorder {self.sortorder} "
f"with lexsort_depth {self._lexsort_depth()}"
)

codes = [
Expand Down Expand Up @@ -1241,7 +1232,7 @@ def _set_names(self, names, level=None, validate=True):
# All items in 'names' need to be hashable:
if not is_hashable(name):
raise TypeError(
"{}.name must be a hashable type".format(type(self).__name__)
f"{type(self).__name__}.name must be a hashable type"
)
self._names[lev] = name

Expand Down Expand Up @@ -1312,8 +1303,8 @@ def _get_level_number(self, level) -> int:
# Note: levels are zero-based
elif level >= self.nlevels:
raise IndexError(
"Too many levels: Index has only %d levels, "
"not %d" % (self.nlevels, level + 1)
f"Too many levels: Index has only {self.nlevels} levels, "
f"not {level + 1}"
)
return level

Expand Down Expand Up @@ -1465,7 +1456,7 @@ def dropna(self, how="any"):
elif how == "all":
indexer = np.all(nans, axis=0)
else:
raise ValueError("invalid how option: {0}".format(how))
raise ValueError(f"invalid how option: {how}")

new_codes = [level_codes[~indexer] for level_codes in self.codes]
return self.copy(codes=new_codes, deep=True)
Expand Down Expand Up @@ -2103,7 +2094,7 @@ def drop(self, codes, level=None, errors="raise"):
loc = loc.nonzero()[0]
inds.extend(loc)
else:
msg = "unsupported indexer of type {}".format(type(loc))
msg = f"unsupported indexer of type {type(loc)}"
raise AssertionError(msg)
except KeyError:
if errors != "ignore":
Expand Down Expand Up @@ -2330,7 +2321,7 @@ def _convert_listlike_indexer(self, keyarr, kind=None):
check = self.levels[0].get_indexer(keyarr)
mask = check == -1
if mask.any():
raise KeyError("%s not in index" % keyarr[mask])
raise KeyError(f"{keyarr[mask]} not in index")

return indexer, keyarr

Expand Down Expand Up @@ -2600,8 +2591,7 @@ def _maybe_to_slice(loc):
keylen = len(key)
if self.nlevels < keylen:
raise KeyError(
"Key length ({0}) exceeds index depth ({1})"
"".format(keylen, self.nlevels)
f"Key length ({keylen}) exceeds index depth ({self.nlevels})"
)

if keylen == self.nlevels and self.is_unique:
Expand Down Expand Up @@ -2917,9 +2907,8 @@ def get_locs(self, seq):
true_slices = [i for (i, s) in enumerate(com.is_true_slices(seq)) if s]
if true_slices and true_slices[-1] >= self.lexsort_depth:
raise UnsortedIndexError(
"MultiIndex slicing requires the index "
"to be lexsorted: slicing on levels {0}, "
"lexsort depth {1}".format(true_slices, self.lexsort_depth)
"MultiIndex slicing requires the index to be lexsorted: slicing "
f"on levels {true_slices}, lexsort depth {self.lexsort_depth}"
)
# indexer
# this is the list of all values that we want to select
Expand Down Expand Up @@ -3261,10 +3250,10 @@ def astype(self, dtype, copy=True):
msg = "> 1 ndim Categorical are not supported at this time"
raise NotImplementedError(msg)
elif not is_object_dtype(dtype):
msg = (
"Setting {cls} dtype to anything other than object is not supported"
).format(cls=type(self))
raise TypeError(msg)
raise TypeError(
f"Setting {type(self)} dtype to anything other "
"than object is not supported"
)
elif copy is True:
return self._shallow_copy()
return self
Expand Down
7 changes: 3 additions & 4 deletions pandas/core/indexes/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,11 +381,10 @@ def inferred_type(self) -> str:
def astype(self, dtype, copy=True):
dtype = pandas_dtype(dtype)
if needs_i8_conversion(dtype):
msg = (
"Cannot convert Float64Index to dtype {dtype}; integer "
raise TypeError(
f"Cannot convert Float64Index to dtype {dtype}; integer "
"values are required for conversion"
).format(dtype=dtype)
raise TypeError(msg)
)
elif is_integer_dtype(dtype) and not is_extension_array_dtype(dtype):
# TODO(jreback); this can change once we have an EA Index type
# GH 13149
Expand Down
Loading