diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index 34838af5fd6e4..43ce8ad4abb45 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -167,9 +167,7 @@ class AbstractMethodError(NotImplementedError): def __init__(self, class_instance, methodtype="method"): types = {"method", "classmethod", "staticmethod", "property"} if methodtype not in types: - msg = "methodtype must be one of {}, got {} instead.".format( - methodtype, types - ) + msg = f"methodtype must be one of {methodtype}, got {types} instead." raise ValueError(msg) self.methodtype = methodtype self.class_instance = class_instance @@ -179,5 +177,5 @@ def __str__(self) -> str: name = self.class_instance.__name__ else: name = type(self.class_instance).__name__ - msg = "This {methodtype} must be defined in the concrete class {name}" + msg = f"This {self.methodtype} must be defined in the concrete class {name}" return msg.format(methodtype=self.methodtype, name=name) diff --git a/pandas/tests/arrays/interval/test_ops.py b/pandas/tests/arrays/interval/test_ops.py index 43601ea301568..a55c33c2f22e9 100644 --- a/pandas/tests/arrays/interval/test_ops.py +++ b/pandas/tests/arrays/interval/test_ops.py @@ -83,8 +83,6 @@ def test_overlaps_na(self, constructor, start_shift): ) def test_overlaps_invalid_type(self, constructor, other): interval_container = constructor.from_breaks(range(5)) - msg = "`other` must be Interval-like, got {other}".format( - other=type(other).__name__ - ) + msg = f"`other` must be Interval-like, got {type(other).__name__}" with pytest.raises(TypeError, match=msg): interval_container.overlaps(other) diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 755cbfb716fcd..c9f96ed516dc5 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -1007,7 +1007,7 @@ def test_cumsum(self, data, expected, numpy): np.cumsum(SparseArray(data), out=out) else: axis = 1 # SparseArray currently 1-D, so only axis = 0 is valid. - msg = "axis\\(={axis}\\) out of bounds".format(axis=axis) + msg = re.escape(f"axis(={axis}) out of bounds") with pytest.raises(ValueError, match=msg): SparseArray(data).cumsum(axis=axis) diff --git a/pandas/tests/arrays/sparse/test_libsparse.py b/pandas/tests/arrays/sparse/test_libsparse.py index a6836c58348b3..7a85ccf271e76 100644 --- a/pandas/tests/arrays/sparse/test_libsparse.py +++ b/pandas/tests/arrays/sparse/test_libsparse.py @@ -596,6 +596,6 @@ def _check_case(xloc, xlen, yloc, ylen, eloc, elen): @pytest.mark.parametrize("opname", ["add", "sub", "mul", "truediv", "floordiv"]) def test_op(self, opname): - sparse_op = getattr(splib, "sparse_{opname}_float64".format(opname=opname)) + sparse_op = getattr(splib, f"sparse_{opname}_float64") python_op = getattr(operator, opname) self._op_tests(sparse_op, python_op) diff --git a/pandas/tests/extension/arrow/arrays.py b/pandas/tests/extension/arrow/arrays.py index 6a28f76e474cc..a4554aca1325e 100644 --- a/pandas/tests/extension/arrow/arrays.py +++ b/pandas/tests/extension/arrow/arrays.py @@ -33,7 +33,7 @@ def construct_from_string(cls, string): if string == cls.name: return cls() else: - raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string)) + raise TypeError(f"Cannot construct a '{cls}' from '{string}'") @classmethod def construct_array_type(cls): @@ -56,7 +56,7 @@ def construct_from_string(cls, string): if string == cls.name: return cls() else: - raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string)) + raise TypeError(f"Cannot construct a '{cls}' from '{string}'") @classmethod def construct_array_type(cls): @@ -79,7 +79,7 @@ def _from_sequence(cls, scalars, dtype=None, copy=False): return cls.from_scalars(scalars) def __repr__(self): - return "{cls}({data})".format(cls=type(self).__name__, data=repr(self._data)) + return f"{type(self).__name__}({repr(self._data)})" def __getitem__(self, item): if pd.api.types.is_scalar(item): diff --git a/pandas/tests/extension/base/printing.py b/pandas/tests/extension/base/printing.py index 5d17a4b0cbee2..ad34a83c7cf71 100644 --- a/pandas/tests/extension/base/printing.py +++ b/pandas/tests/extension/base/printing.py @@ -19,7 +19,7 @@ def test_array_repr(self, data, size): result = repr(data) assert type(data).__name__ in result - assert "Length: {}".format(len(data)) in result + assert f"Length: {len(data)}" in result assert str(data.dtype) in result if size == "big": assert "..." in result diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index f9ba4b7a8ba16..0c2f1e845909a 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -23,7 +23,7 @@ def __init__(self, context=None): self.context = context or decimal.getcontext() def __repr__(self) -> str: - return "DecimalDtype(context={})".format(self.context) + return f"DecimalDtype(context={self.context})" @classmethod def construct_array_type(cls): @@ -40,7 +40,7 @@ def construct_from_string(cls, string): if string == cls.name: return cls() else: - raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string)) + raise TypeError(f"Cannot construct a '{cls}' from '{string}'") @property def _is_numeric(self): @@ -178,9 +178,7 @@ def _reduce(self, name, skipna=True, **kwargs): try: op = getattr(self.data, name) except AttributeError: - raise NotImplementedError( - "decimal does not support the {} operation".format(name) - ) + raise NotImplementedError(f"decimal does not support the {name} operation") return op(axis=0) diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index a29f910261b58..f9229e8066be4 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -146,9 +146,7 @@ def test_resample_basic_grouper(series): def test_resample_string_kwargs(series, keyword, value): # see gh-19303 # Check that wrong keyword argument strings raise an error - msg = "Unsupported value {value} for `{keyword}`".format( - value=value, keyword=keyword - ) + msg = f"Unsupported value {value} for `{keyword}`" with pytest.raises(ValueError, match=msg): series.resample("5min", **({keyword: value})) diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py index 574182ae99c5c..4c27d48cff6fd 100644 --- a/pandas/tests/resample/test_time_grouper.py +++ b/pandas/tests/resample/test_time_grouper.py @@ -89,7 +89,7 @@ def test_fails_on_no_datetime_index(name, func): msg = ( "Only valid with DatetimeIndex, TimedeltaIndex " - "or PeriodIndex, but got an instance of '{}'".format(name) + f"or PeriodIndex, but got an instance of '{name}'" ) with pytest.raises(TypeError, match=msg): df.groupby(Grouper(freq="D")) diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 79608f4fb3cde..e709db980b721 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -141,7 +141,7 @@ def test_round_nat(klass, method, freq): ) def test_nat_methods_raise(method): # see gh-9513, gh-17329 - msg = "NaTType does not support {method}".format(method=method) + msg = f"NaTType does not support {method}" with pytest.raises(ValueError, match=msg): getattr(NaT, method)() diff --git a/pandas/tests/tseries/offsets/common.py b/pandas/tests/tseries/offsets/common.py index fbf4454109ec0..a097636bbf0b4 100644 --- a/pandas/tests/tseries/offsets/common.py +++ b/pandas/tests/tseries/offsets/common.py @@ -13,18 +13,14 @@ def assert_offset_equal(offset, base, expected): assert actual_apply == expected except AssertionError: raise AssertionError( - "\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})" - "\nAt Date: {base}".format( - expected=expected, actual=actual, offset=offset, base=base - ) + f"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})" + f"\nAt Date: {base}" ) def assert_onOffset(offset, date, expected): actual = offset.onOffset(date) assert actual == expected, ( - "\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})" - "\nAt Date: {date}".format( - expected=expected, actual=actual, offset=offset, date=date - ) + f"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})" + f"\nAt Date: {date}" ) diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 898060d011372..9ff5fb41957b9 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -243,7 +243,7 @@ def infer_freq(index, warn=True): ): raise TypeError( "cannot infer freq from a non-convertible dtype " - "on a Series of {dtype}".format(dtype=index.dtype) + f"on a Series of {index.dtype}" ) index = values @@ -260,8 +260,7 @@ def infer_freq(index, warn=True): if isinstance(index, pd.Index) and not isinstance(index, pd.DatetimeIndex): if isinstance(index, (pd.Int64Index, pd.Float64Index)): raise TypeError( - "cannot infer freq from a non-convertible index " - "type {type}".format(type=type(index)) + f"cannot infer freq from a non-convertible index type {type(index)}" ) index = index.values @@ -393,7 +392,7 @@ def _infer_daily_rule(self): if annual_rule: nyears = self.ydiffs[0] month = MONTH_ALIASES[self.rep_stamp.month] - alias = "{prefix}-{month}".format(prefix=annual_rule, month=month) + alias = f"{annual_rule}-{month}" return _maybe_add_count(alias, nyears) quarterly_rule = self._get_quarterly_rule() @@ -401,7 +400,7 @@ def _infer_daily_rule(self): nquarters = self.mdiffs[0] / 3 mod_dict = {0: 12, 2: 11, 1: 10} month = MONTH_ALIASES[mod_dict[self.rep_stamp.month % 3]] - alias = "{prefix}-{month}".format(prefix=quarterly_rule, month=month) + alias = f"{quarterly_rule}-{month}" return _maybe_add_count(alias, nquarters) monthly_rule = self._get_monthly_rule() @@ -413,7 +412,7 @@ def _infer_daily_rule(self): if days % 7 == 0: # Weekly day = int_to_weekday[self.rep_stamp.weekday()] - return _maybe_add_count("W-{day}".format(day=day), days / 7) + return _maybe_add_count(f"W-{day}", days / 7) else: return _maybe_add_count("D", days) @@ -485,7 +484,7 @@ def _get_wom_rule(self): week = week_of_months[0] + 1 wd = int_to_weekday[weekdays[0]] - return "WOM-{week}{weekday}".format(week=week, weekday=wd) + return f"WOM-{week}{wd}" class _TimedeltaFrequencyInferer(_FrequencyInferer): @@ -495,7 +494,7 @@ def _infer_daily_rule(self): if days % 7 == 0: # Weekly wd = int_to_weekday[self.rep_stamp.weekday()] - alias = "W-{weekday}".format(weekday=wd) + alias = f"W-{wd}" return _maybe_add_count(alias, days / 7) else: return _maybe_add_count("D", days) @@ -509,6 +508,6 @@ def _maybe_add_count(base, count): if count != 1: assert count == int(count) count = int(count) - return "{count}{base}".format(count=count, base=base) + return f"{count}{base}" else: return base