Skip to content

Commit af6716b

Browse files
ForTimeBeingproost
authored andcommitted
String formatting > fstring (pandas-dev#29892)
1 parent 3d4910e commit af6716b

File tree

12 files changed

+27
-40
lines changed

12 files changed

+27
-40
lines changed

pandas/errors/__init__.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,7 @@ class AbstractMethodError(NotImplementedError):
167167
def __init__(self, class_instance, methodtype="method"):
168168
types = {"method", "classmethod", "staticmethod", "property"}
169169
if methodtype not in types:
170-
msg = "methodtype must be one of {}, got {} instead.".format(
171-
methodtype, types
172-
)
170+
msg = f"methodtype must be one of {methodtype}, got {types} instead."
173171
raise ValueError(msg)
174172
self.methodtype = methodtype
175173
self.class_instance = class_instance
@@ -179,5 +177,5 @@ def __str__(self) -> str:
179177
name = self.class_instance.__name__
180178
else:
181179
name = type(self.class_instance).__name__
182-
msg = "This {methodtype} must be defined in the concrete class {name}"
180+
msg = f"This {self.methodtype} must be defined in the concrete class {name}"
183181
return msg.format(methodtype=self.methodtype, name=name)

pandas/tests/arrays/interval/test_ops.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,6 @@ def test_overlaps_na(self, constructor, start_shift):
8383
)
8484
def test_overlaps_invalid_type(self, constructor, other):
8585
interval_container = constructor.from_breaks(range(5))
86-
msg = "`other` must be Interval-like, got {other}".format(
87-
other=type(other).__name__
88-
)
86+
msg = f"`other` must be Interval-like, got {type(other).__name__}"
8987
with pytest.raises(TypeError, match=msg):
9088
interval_container.overlaps(other)

pandas/tests/arrays/sparse/test_array.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1007,7 +1007,7 @@ def test_cumsum(self, data, expected, numpy):
10071007
np.cumsum(SparseArray(data), out=out)
10081008
else:
10091009
axis = 1 # SparseArray currently 1-D, so only axis = 0 is valid.
1010-
msg = "axis\\(={axis}\\) out of bounds".format(axis=axis)
1010+
msg = re.escape(f"axis(={axis}) out of bounds")
10111011
with pytest.raises(ValueError, match=msg):
10121012
SparseArray(data).cumsum(axis=axis)
10131013

pandas/tests/arrays/sparse/test_libsparse.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -596,6 +596,6 @@ def _check_case(xloc, xlen, yloc, ylen, eloc, elen):
596596

597597
@pytest.mark.parametrize("opname", ["add", "sub", "mul", "truediv", "floordiv"])
598598
def test_op(self, opname):
599-
sparse_op = getattr(splib, "sparse_{opname}_float64".format(opname=opname))
599+
sparse_op = getattr(splib, f"sparse_{opname}_float64")
600600
python_op = getattr(operator, opname)
601601
self._op_tests(sparse_op, python_op)

pandas/tests/extension/arrow/arrays.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def construct_from_string(cls, string):
3333
if string == cls.name:
3434
return cls()
3535
else:
36-
raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string))
36+
raise TypeError(f"Cannot construct a '{cls}' from '{string}'")
3737

3838
@classmethod
3939
def construct_array_type(cls):
@@ -56,7 +56,7 @@ def construct_from_string(cls, string):
5656
if string == cls.name:
5757
return cls()
5858
else:
59-
raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string))
59+
raise TypeError(f"Cannot construct a '{cls}' from '{string}'")
6060

6161
@classmethod
6262
def construct_array_type(cls):
@@ -79,7 +79,7 @@ def _from_sequence(cls, scalars, dtype=None, copy=False):
7979
return cls.from_scalars(scalars)
8080

8181
def __repr__(self):
82-
return "{cls}({data})".format(cls=type(self).__name__, data=repr(self._data))
82+
return f"{type(self).__name__}({repr(self._data)})"
8383

8484
def __getitem__(self, item):
8585
if pd.api.types.is_scalar(item):

pandas/tests/extension/base/printing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def test_array_repr(self, data, size):
1919

2020
result = repr(data)
2121
assert type(data).__name__ in result
22-
assert "Length: {}".format(len(data)) in result
22+
assert f"Length: {len(data)}" in result
2323
assert str(data.dtype) in result
2424
if size == "big":
2525
assert "..." in result

pandas/tests/extension/decimal/array.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def __init__(self, context=None):
2323
self.context = context or decimal.getcontext()
2424

2525
def __repr__(self) -> str:
26-
return "DecimalDtype(context={})".format(self.context)
26+
return f"DecimalDtype(context={self.context})"
2727

2828
@classmethod
2929
def construct_array_type(cls):
@@ -40,7 +40,7 @@ def construct_from_string(cls, string):
4040
if string == cls.name:
4141
return cls()
4242
else:
43-
raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string))
43+
raise TypeError(f"Cannot construct a '{cls}' from '{string}'")
4444

4545
@property
4646
def _is_numeric(self):
@@ -178,9 +178,7 @@ def _reduce(self, name, skipna=True, **kwargs):
178178
try:
179179
op = getattr(self.data, name)
180180
except AttributeError:
181-
raise NotImplementedError(
182-
"decimal does not support the {} operation".format(name)
183-
)
181+
raise NotImplementedError(f"decimal does not support the {name} operation")
184182
return op(axis=0)
185183

186184

pandas/tests/resample/test_datetime_index.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,7 @@ def test_resample_basic_grouper(series):
146146
def test_resample_string_kwargs(series, keyword, value):
147147
# see gh-19303
148148
# Check that wrong keyword argument strings raise an error
149-
msg = "Unsupported value {value} for `{keyword}`".format(
150-
value=value, keyword=keyword
151-
)
149+
msg = f"Unsupported value {value} for `{keyword}`"
152150
with pytest.raises(ValueError, match=msg):
153151
series.resample("5min", **({keyword: value}))
154152

pandas/tests/resample/test_time_grouper.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def test_fails_on_no_datetime_index(name, func):
8989

9090
msg = (
9191
"Only valid with DatetimeIndex, TimedeltaIndex "
92-
"or PeriodIndex, but got an instance of '{}'".format(name)
92+
f"or PeriodIndex, but got an instance of '{name}'"
9393
)
9494
with pytest.raises(TypeError, match=msg):
9595
df.groupby(Grouper(freq="D"))

pandas/tests/scalar/test_nat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ def test_round_nat(klass, method, freq):
141141
)
142142
def test_nat_methods_raise(method):
143143
# see gh-9513, gh-17329
144-
msg = "NaTType does not support {method}".format(method=method)
144+
msg = f"NaTType does not support {method}"
145145

146146
with pytest.raises(ValueError, match=msg):
147147
getattr(NaT, method)()

pandas/tests/tseries/offsets/common.py

+4-8
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,14 @@ def assert_offset_equal(offset, base, expected):
1313
assert actual_apply == expected
1414
except AssertionError:
1515
raise AssertionError(
16-
"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})"
17-
"\nAt Date: {base}".format(
18-
expected=expected, actual=actual, offset=offset, base=base
19-
)
16+
f"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})"
17+
f"\nAt Date: {base}"
2018
)
2119

2220

2321
def assert_onOffset(offset, date, expected):
2422
actual = offset.onOffset(date)
2523
assert actual == expected, (
26-
"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})"
27-
"\nAt Date: {date}".format(
28-
expected=expected, actual=actual, offset=offset, date=date
29-
)
24+
f"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})"
25+
f"\nAt Date: {date}"
3026
)

pandas/tseries/frequencies.py

+8-9
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ def infer_freq(index, warn: bool = True) -> Optional[str]:
245245
):
246246
raise TypeError(
247247
"cannot infer freq from a non-convertible dtype "
248-
"on a Series of {dtype}".format(dtype=index.dtype)
248+
f"on a Series of {index.dtype}"
249249
)
250250
index = values
251251

@@ -263,8 +263,7 @@ def infer_freq(index, warn: bool = True) -> Optional[str]:
263263
if isinstance(index, pd.Index) and not isinstance(index, pd.DatetimeIndex):
264264
if isinstance(index, (pd.Int64Index, pd.Float64Index)):
265265
raise TypeError(
266-
"cannot infer freq from a non-convertible index "
267-
"type {type}".format(type=type(index))
266+
f"cannot infer freq from a non-convertible index type {type(index)}"
268267
)
269268
index = index.values
270269

@@ -396,15 +395,15 @@ def _infer_daily_rule(self) -> Optional[str]:
396395
if annual_rule:
397396
nyears = self.ydiffs[0]
398397
month = MONTH_ALIASES[self.rep_stamp.month]
399-
alias = "{prefix}-{month}".format(prefix=annual_rule, month=month)
398+
alias = f"{annual_rule}-{month}"
400399
return _maybe_add_count(alias, nyears)
401400

402401
quarterly_rule = self._get_quarterly_rule()
403402
if quarterly_rule:
404403
nquarters = self.mdiffs[0] / 3
405404
mod_dict = {0: 12, 2: 11, 1: 10}
406405
month = MONTH_ALIASES[mod_dict[self.rep_stamp.month % 3]]
407-
alias = "{prefix}-{month}".format(prefix=quarterly_rule, month=month)
406+
alias = f"{quarterly_rule}-{month}"
408407
return _maybe_add_count(alias, nquarters)
409408

410409
monthly_rule = self._get_monthly_rule()
@@ -416,7 +415,7 @@ def _infer_daily_rule(self) -> Optional[str]:
416415
if days % 7 == 0:
417416
# Weekly
418417
day = int_to_weekday[self.rep_stamp.weekday()]
419-
return _maybe_add_count("W-{day}".format(day=day), days / 7)
418+
return _maybe_add_count(f"W-{day}", days / 7)
420419
else:
421420
return _maybe_add_count("D", days)
422421

@@ -490,7 +489,7 @@ def _get_wom_rule(self) -> Optional[str]:
490489
week = week_of_months[0] + 1
491490
wd = int_to_weekday[weekdays[0]]
492491

493-
return "WOM-{week}{weekday}".format(week=week, weekday=wd)
492+
return f"WOM-{week}{wd}"
494493

495494

496495
class _TimedeltaFrequencyInferer(_FrequencyInferer):
@@ -500,7 +499,7 @@ def _infer_daily_rule(self):
500499
if days % 7 == 0:
501500
# Weekly
502501
wd = int_to_weekday[self.rep_stamp.weekday()]
503-
alias = "W-{weekday}".format(weekday=wd)
502+
alias = f"W-{wd}"
504503
return _maybe_add_count(alias, days / 7)
505504
else:
506505
return _maybe_add_count("D", days)
@@ -514,6 +513,6 @@ def _maybe_add_count(base: str, count: float) -> str:
514513
if count != 1:
515514
assert count == int(count)
516515
count = int(count)
517-
return "{count}{base}".format(count=count, base=base)
516+
return f"{count}{base}"
518517
else:
519518
return base

0 commit comments

Comments
 (0)