Skip to content

Commit 9223ff5

Browse files
AlpAribaljreback
authored andcommitted
STY: change .format() to fstring (#30116)
1 parent 26f76d5 commit 9223ff5

File tree

3 files changed

+50
-86
lines changed

3 files changed

+50
-86
lines changed

pandas/core/arrays/base.py

+5-12
Original file line numberDiff line numberDiff line change
@@ -520,8 +520,8 @@ def fillna(self, value=None, method=None, limit=None):
520520
if is_array_like(value):
521521
if len(value) != len(self):
522522
raise ValueError(
523-
"Length of 'value' does not match. Got ({}) "
524-
" expected {}".format(len(value), len(self))
523+
f"Length of 'value' does not match. Got ({len(value)}) "
524+
f"expected {len(self)}"
525525
)
526526
value = value[mask]
527527

@@ -918,17 +918,14 @@ def view(self, dtype=None) -> Union[ABCExtensionArray, np.ndarray]:
918918
def __repr__(self) -> str:
919919
from pandas.io.formats.printing import format_object_summary
920920

921-
template = "{class_name}{data}\nLength: {length}, dtype: {dtype}"
922921
# the short repr has no trailing newline, while the truncated
923922
# repr does. So we include a newline in our template, and strip
924923
# any trailing newlines from format_object_summary
925924
data = format_object_summary(
926925
self, self._formatter(), indent_for_name=False
927926
).rstrip(", \n")
928-
class_name = "<{}>\n".format(type(self).__name__)
929-
return template.format(
930-
class_name=class_name, data=data, length=len(self), dtype=self.dtype
931-
)
927+
class_name = f"<{type(self).__name__}>\n"
928+
return f"{class_name}{data}\nLength: {len(self)}, dtype: {self.dtype}"
932929

933930
def _formatter(self, boxed: bool = False) -> Callable[[Any], Optional[str]]:
934931
"""Formatting function for scalar values.
@@ -1044,11 +1041,7 @@ def _reduce(self, name, skipna=True, **kwargs):
10441041
------
10451042
TypeError : subclass does not define reductions
10461043
"""
1047-
raise TypeError(
1048-
"cannot perform {name} with type {dtype}".format(
1049-
name=name, dtype=self.dtype
1050-
)
1051-
)
1044+
raise TypeError(f"cannot perform {name} with type {self.dtype}")
10521045

10531046

10541047
class ExtensionOpsMixin:

pandas/core/arrays/datetimelike.py

+28-51
Original file line numberDiff line numberDiff line change
@@ -470,10 +470,11 @@ def __setitem__(
470470
key = cast(Sequence, key)
471471
if len(key) != len(value) and not com.is_bool_indexer(key):
472472
msg = (
473-
"shape mismatch: value array of length '{}' does "
474-
"not match indexing result of length '{}'."
473+
f"shape mismatch: value array of length '{len(key)}' "
474+
"does not match indexing result of length "
475+
f"'{len(value)}'."
475476
)
476-
raise ValueError(msg.format(len(key), len(value)))
477+
raise ValueError(msg)
477478
elif not len(key):
478479
return
479480

@@ -487,12 +488,10 @@ def __setitem__(
487488
value = iNaT
488489
else:
489490
msg = (
490-
"'value' should be a '{scalar}', 'NaT', or array of those. "
491-
"Got '{typ}' instead."
492-
)
493-
raise TypeError(
494-
msg.format(scalar=self._scalar_type.__name__, typ=type(value).__name__)
491+
f"'value' should be a '{self._scalar_type.__name__}', 'NaT', "
492+
f"or array of those. Got '{type(value).__name__}' instead."
495493
)
494+
raise TypeError(msg)
496495
self._data[key] = value
497496
self._maybe_clear_freq()
498497

@@ -532,8 +531,8 @@ def astype(self, dtype, copy=True):
532531
) or is_float_dtype(dtype):
533532
# disallow conversion between datetime/timedelta,
534533
# and conversions for any datetimelike to float
535-
msg = "Cannot cast {name} to dtype {dtype}"
536-
raise TypeError(msg.format(name=type(self).__name__, dtype=dtype))
534+
msg = f"Cannot cast {type(self).__name__} to dtype {dtype}"
535+
raise TypeError(msg)
537536
elif is_categorical_dtype(dtype):
538537
return Categorical(self, dtype=dtype)
539538
else:
@@ -637,9 +636,7 @@ def searchsorted(self, value, side="left", sorter=None):
637636
value = self._scalar_from_string(value)
638637

639638
if not (isinstance(value, (self._scalar_type, type(self))) or isna(value)):
640-
raise ValueError(
641-
"Unexpected type for 'value': {valtype}".format(valtype=type(value))
642-
)
639+
raise ValueError(f"Unexpected type for 'value': {type(value)}")
643640

644641
self._check_compatible_with(value)
645642
if isinstance(value, type(self)):
@@ -759,8 +756,8 @@ def fillna(self, value=None, method=None, limit=None):
759756
if is_array_like(value):
760757
if len(value) != len(self):
761758
raise ValueError(
762-
"Length of 'value' does not match. Got ({}) "
763-
" expected {}".format(len(value), len(self))
759+
f"Length of 'value' does not match. Got ({len(value)}) "
760+
f" expected {len(self)}"
764761
)
765762
value = value[mask]
766763

@@ -880,10 +877,8 @@ def _validate_frequency(cls, index, freq, **kwargs):
880877
# raise a ValueError, which we re-raise with a more targeted
881878
# message.
882879
raise ValueError(
883-
"Inferred frequency {infer} from passed values "
884-
"does not conform to passed frequency {passed}".format(
885-
infer=inferred, passed=freq.freqstr
886-
)
880+
f"Inferred frequency {inferred} from passed values "
881+
f"does not conform to passed frequency {freq.freqstr}"
887882
)
888883

889884
# monotonicity/uniqueness properties are called via frequencies.infer_freq,
@@ -922,27 +917,21 @@ def _is_unique(self):
922917
def _add_datetimelike_scalar(self, other):
923918
# Overriden by TimedeltaArray
924919
raise TypeError(
925-
"cannot add {cls} and {typ}".format(
926-
cls=type(self).__name__, typ=type(other).__name__
927-
)
920+
f"cannot add {type(self).__name__} and " f"{type(other).__name__}"
928921
)
929922

930923
_add_datetime_arraylike = _add_datetimelike_scalar
931924

932925
def _sub_datetimelike_scalar(self, other):
933926
# Overridden by DatetimeArray
934927
assert other is not NaT
935-
raise TypeError(
936-
"cannot subtract a datelike from a {cls}".format(cls=type(self).__name__)
937-
)
928+
raise TypeError(f"cannot subtract a datelike from a {type(self).__name__}")
938929

939930
_sub_datetime_arraylike = _sub_datetimelike_scalar
940931

941932
def _sub_period(self, other):
942933
# Overriden by PeriodArray
943-
raise TypeError(
944-
"cannot subtract Period from a {cls}".format(cls=type(self).__name__)
945-
)
934+
raise TypeError(f"cannot subtract Period from a {type(self).__name__}")
946935

947936
def _add_offset(self, offset):
948937
raise AbstractMethodError(self)
@@ -1022,9 +1011,7 @@ def _add_nat(self):
10221011
"""
10231012
if is_period_dtype(self):
10241013
raise TypeError(
1025-
"Cannot add {cls} and {typ}".format(
1026-
cls=type(self).__name__, typ=type(NaT).__name__
1027-
)
1014+
f"Cannot add {type(self).__name__} and {type(NaT).__name__}"
10281015
)
10291016

10301017
# GH#19124 pd.NaT is treated like a timedelta for both timedelta
@@ -1064,9 +1051,7 @@ def _sub_period_array(self, other):
10641051
"""
10651052
if not is_period_dtype(self):
10661053
raise TypeError(
1067-
"cannot subtract {dtype}-dtype from {cls}".format(
1068-
dtype=other.dtype, cls=type(self).__name__
1069-
)
1054+
f"cannot subtract {other.dtype}-dtype from {type(self).__name__}"
10701055
)
10711056

10721057
if len(self) != len(other):
@@ -1140,7 +1125,7 @@ def _addsub_offset_array(self, other, op):
11401125

11411126
warnings.warn(
11421127
"Adding/subtracting array of DateOffsets to "
1143-
"{cls} not vectorized".format(cls=type(self).__name__),
1128+
f"{type(self).__name__} not vectorized",
11441129
PerformanceWarning,
11451130
)
11461131

@@ -1313,17 +1298,11 @@ def __rsub__(self, other):
13131298
# GH#19959 datetime - datetime is well-defined as timedelta,
13141299
# but any other type - datetime is not well-defined.
13151300
raise TypeError(
1316-
"cannot subtract {cls} from {typ}".format(
1317-
cls=type(self).__name__, typ=type(other).__name__
1318-
)
1301+
f"cannot subtract {type(self).__name__} from {type(other).__name__}"
13191302
)
13201303
elif is_period_dtype(self.dtype) and is_timedelta64_dtype(other):
13211304
# TODO: Can we simplify/generalize these cases at all?
1322-
raise TypeError(
1323-
"cannot subtract {cls} from {dtype}".format(
1324-
cls=type(self).__name__, dtype=other.dtype
1325-
)
1326-
)
1305+
raise TypeError(f"cannot subtract {type(self).__name__} from {other.dtype}")
13271306
elif is_timedelta64_dtype(self.dtype):
13281307
if lib.is_integer(other) or is_integer_dtype(other):
13291308
# need to subtract before negating, since that flips freq
@@ -1472,9 +1451,9 @@ def mean(self, skipna=True):
14721451
if is_period_dtype(self):
14731452
# See discussion in GH#24757
14741453
raise TypeError(
1475-
"mean is not implemented for {cls} since the meaning is "
1476-
"ambiguous. An alternative is "
1477-
"obj.to_timestamp(how='start').mean()".format(cls=type(self).__name__)
1454+
f"mean is not implemented for {type(self).__name__} since the "
1455+
"meaning is ambiguous. An alternative is "
1456+
"obj.to_timestamp(how='start').mean()"
14781457
)
14791458

14801459
mask = self.isna()
@@ -1520,9 +1499,7 @@ def validate_periods(periods):
15201499
if lib.is_float(periods):
15211500
periods = int(periods)
15221501
elif not lib.is_integer(periods):
1523-
raise TypeError(
1524-
"periods must be a number, got {periods}".format(periods=periods)
1525-
)
1502+
raise TypeError(f"periods must be a number, got {periods}")
15261503
return periods
15271504

15281505

@@ -1583,9 +1560,9 @@ def validate_inferred_freq(freq, inferred_freq, freq_infer):
15831560
if inferred_freq is not None:
15841561
if freq is not None and freq != inferred_freq:
15851562
raise ValueError(
1586-
"Inferred frequency {inferred} from passed "
1563+
f"Inferred frequency {inferred_freq} from passed "
15871564
"values does not conform to passed frequency "
1588-
"{passed}".format(inferred=inferred_freq, passed=freq.freqstr)
1565+
f"{freq.freqstr}"
15891566
)
15901567
elif freq is None:
15911568
freq = inferred_freq

pandas/core/arrays/datetimes.py

+17-23
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def _dt_array_cmp(cls, op):
150150
"""
151151
Wrap comparison operations to convert datetime-like to datetime64
152152
"""
153-
opname = "__{name}__".format(name=op.__name__)
153+
opname = f"__{op.__name__}__"
154154
nat_result = opname == "__ne__"
155155

156156
@unpack_zerodim_and_defer(opname)
@@ -338,9 +338,9 @@ def __init__(self, values, dtype=_NS_DTYPE, freq=None, copy=False):
338338
if not timezones.tz_compare(dtz, values.tz):
339339
msg = (
340340
"Timezone of the array and 'dtype' do not match. "
341-
"'{}' != '{}'"
341+
f"'{dtz}' != '{values.tz}'"
342342
)
343-
raise TypeError(msg.format(dtz, values.tz))
343+
raise TypeError(msg)
344344
elif values.tz:
345345
dtype = values.dtype
346346
# freq = validate_values_freq(values, freq)
@@ -350,10 +350,11 @@ def __init__(self, values, dtype=_NS_DTYPE, freq=None, copy=False):
350350

351351
if not isinstance(values, np.ndarray):
352352
msg = (
353-
"Unexpected type '{}'. 'values' must be a DatetimeArray "
354-
"ndarray, or Series or Index containing one of those."
353+
f"Unexpected type '{type(values).__name__}'. 'values' must be "
354+
"a DatetimeArray ndarray, or Series or Index containing one of"
355+
" those."
355356
)
356-
raise ValueError(msg.format(type(values).__name__))
357+
raise ValueError(msg)
357358
if values.ndim != 1:
358359
raise ValueError("Only 1-dimensional input arrays are supported.")
359360

@@ -366,9 +367,9 @@ def __init__(self, values, dtype=_NS_DTYPE, freq=None, copy=False):
366367
if values.dtype != _NS_DTYPE:
367368
msg = (
368369
"The dtype of 'values' is incorrect. Must be 'datetime64[ns]'."
369-
" Got {} instead."
370+
f" Got {values.dtype} instead."
370371
)
371-
raise ValueError(msg.format(values.dtype))
372+
raise ValueError(msg)
372373

373374
dtype = _validate_dt64_dtype(dtype)
374375

@@ -577,11 +578,7 @@ def _check_compatible_with(self, other):
577578
if other is NaT:
578579
return
579580
if not timezones.tz_compare(self.tz, other.tz):
580-
raise ValueError(
581-
"Timezones don't match. '{own} != {other}'".format(
582-
own=self.tz, other=other.tz
583-
)
584-
)
581+
raise ValueError(f"Timezones don't match. '{self.tz} != {other.tz}'")
585582

586583
def _maybe_clear_freq(self):
587584
self._freq = None
@@ -732,10 +729,7 @@ def _validate_fill_value(self, fill_value):
732729
self._assert_tzawareness_compat(fill_value)
733730
fill_value = Timestamp(fill_value).value
734731
else:
735-
raise ValueError(
736-
"'fill_value' should be a Timestamp. "
737-
"Got '{got}'.".format(got=fill_value)
738-
)
732+
raise ValueError(f"'fill_value' should be a Timestamp. Got '{fill_value}'.")
739733
return fill_value
740734

741735
# -----------------------------------------------------------------
@@ -799,8 +793,8 @@ def _sub_datetime_arraylike(self, other):
799793
if not self._has_same_tz(other):
800794
# require tz compat
801795
raise TypeError(
802-
"{cls} subtraction must have the same "
803-
"timezones or no timezones".format(cls=type(self).__name__)
796+
f"{type(self).__name__} subtraction must have the same "
797+
"timezones or no timezones"
804798
)
805799

806800
self_i8 = self.asi8
@@ -2119,8 +2113,8 @@ def maybe_infer_tz(tz, inferred_tz):
21192113
pass
21202114
elif not timezones.tz_compare(tz, inferred_tz):
21212115
raise TypeError(
2122-
"data is already tz-aware {inferred_tz}, unable to "
2123-
"set specified tz: {tz}".format(inferred_tz=inferred_tz, tz=tz)
2116+
f"data is already tz-aware {inferred_tz}, unable to "
2117+
f"set specified tz: {tz}"
21242118
)
21252119
return tz
21262120

@@ -2164,8 +2158,8 @@ def _validate_dt64_dtype(dtype):
21642158
dtype, (np.dtype, DatetimeTZDtype)
21652159
):
21662160
raise ValueError(
2167-
"Unexpected value for 'dtype': '{dtype}'. "
2168-
"Must be 'datetime64[ns]' or DatetimeTZDtype'.".format(dtype=dtype)
2161+
f"Unexpected value for 'dtype': '{dtype}'. "
2162+
"Must be 'datetime64[ns]' or DatetimeTZDtype'."
21692163
)
21702164
return dtype
21712165

0 commit comments

Comments
 (0)