Skip to content

Commit 4edf938

Browse files
simonjayhawkinsjreback
authored andcommitted
TST/CLN: replace %s formatting syntax with .format in tests (#27324)
1 parent c74a853 commit 4edf938

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

61 files changed

+239
-172
lines changed

pandas/tests/arrays/categorical/test_dtypes.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -92,20 +92,22 @@ def test_codes_dtypes(self):
9292
result = Categorical(["foo", "bar", "baz"])
9393
assert result.codes.dtype == "int8"
9494

95-
result = Categorical(["foo%05d" % i for i in range(400)])
95+
result = Categorical(["foo{i:05d}".format(i=i) for i in range(400)])
9696
assert result.codes.dtype == "int16"
9797

98-
result = Categorical(["foo%05d" % i for i in range(40000)])
98+
result = Categorical(["foo{i:05d}".format(i=i) for i in range(40000)])
9999
assert result.codes.dtype == "int32"
100100

101101
# adding cats
102102
result = Categorical(["foo", "bar", "baz"])
103103
assert result.codes.dtype == "int8"
104-
result = result.add_categories(["foo%05d" % i for i in range(400)])
104+
result = result.add_categories(["foo{i:05d}".format(i=i) for i in range(400)])
105105
assert result.codes.dtype == "int16"
106106

107107
# removing cats
108-
result = result.remove_categories(["foo%05d" % i for i in range(300)])
108+
result = result.remove_categories(
109+
["foo{i:05d}".format(i=i) for i in range(300)]
110+
)
109111
assert result.codes.dtype == "int8"
110112

111113
@pytest.mark.parametrize("ordered", [True, False])

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_%s_float64" % opname)
599+
sparse_op = getattr(splib, "sparse_{opname}_float64".format(opname=opname))
600600
python_op = getattr(operator, opname)
601601
self._op_tests(sparse_op, python_op)

pandas/tests/computation/test_eval.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -736,16 +736,16 @@ def test_float_truncation(self):
736736

737737
df = pd.DataFrame({"A": [1000000000.0009, 1000000000.0011, 1000000000.0015]})
738738
cutoff = 1000000000.0006
739-
result = df.query("A < %.4f" % cutoff)
739+
result = df.query("A < {cutoff:.4f}".format(cutoff=cutoff))
740740
assert result.empty
741741

742742
cutoff = 1000000000.0010
743-
result = df.query("A > %.4f" % cutoff)
743+
result = df.query("A > {cutoff:.4f}".format(cutoff=cutoff))
744744
expected = df.loc[[1, 2], :]
745745
tm.assert_frame_equal(expected, result)
746746

747747
exact = 1000000000.0011
748-
result = df.query("A == %.4f" % exact)
748+
result = df.query("A == {exact:.4f}".format(exact=exact))
749749
expected = df.loc[[1], :]
750750
tm.assert_frame_equal(expected, result)
751751

pandas/tests/dtypes/test_inference.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1349,7 +1349,7 @@ def test_is_scalar_pandas_containers(self):
13491349

13501350
def test_datetimeindex_from_empty_datetime64_array():
13511351
for unit in ["ms", "us", "ns"]:
1352-
idx = DatetimeIndex(np.array([], dtype="datetime64[%s]" % unit))
1352+
idx = DatetimeIndex(np.array([], dtype="datetime64[{unit}]".format(unit=unit)))
13531353
assert len(idx) == 0
13541354

13551355

pandas/tests/frame/test_alter_axes.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ def __init__(self, name, color):
342342
self.color = color
343343

344344
def __str__(self):
345-
return "<Thing %r>" % (self.name,)
345+
return "<Thing {self.name!r}>".format(self=self)
346346

347347
# necessary for pretty KeyError
348348
__repr__ = __str__
@@ -419,7 +419,7 @@ def __init__(self, name, color):
419419
self.color = color
420420

421421
def __str__(self):
422-
return "<Thing %r>" % (self.name,)
422+
return "<Thing {self.name!r}>".format(self=self)
423423

424424
thing1 = Thing("One", "red")
425425
thing2 = Thing("Two", "blue")

pandas/tests/frame/test_api.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -74,19 +74,19 @@ def test_get_value(self, float_frame):
7474

7575
def test_add_prefix_suffix(self, float_frame):
7676
with_prefix = float_frame.add_prefix("foo#")
77-
expected = pd.Index(["foo#%s" % c for c in float_frame.columns])
77+
expected = pd.Index(["foo#{c}".format(c=c) for c in float_frame.columns])
7878
tm.assert_index_equal(with_prefix.columns, expected)
7979

8080
with_suffix = float_frame.add_suffix("#foo")
81-
expected = pd.Index(["%s#foo" % c for c in float_frame.columns])
81+
expected = pd.Index(["{c}#foo".format(c=c) for c in float_frame.columns])
8282
tm.assert_index_equal(with_suffix.columns, expected)
8383

8484
with_pct_prefix = float_frame.add_prefix("%")
85-
expected = pd.Index(["%{}".format(c) for c in float_frame.columns])
85+
expected = pd.Index(["%{c}".format(c=c) for c in float_frame.columns])
8686
tm.assert_index_equal(with_pct_prefix.columns, expected)
8787

8888
with_pct_suffix = float_frame.add_suffix("%")
89-
expected = pd.Index(["{}%".format(c) for c in float_frame.columns])
89+
expected = pd.Index(["{c}%".format(c=c) for c in float_frame.columns])
9090
tm.assert_index_equal(with_pct_suffix.columns, expected)
9191

9292
def test_get_axis(self, float_frame):

pandas/tests/frame/test_constructors.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ def test_constructor_ordereddict(self):
264264
nitems = 100
265265
nums = list(range(nitems))
266266
random.shuffle(nums)
267-
expected = ["A%d" % i for i in nums]
267+
expected = ["A{i:d}".format(i=i) for i in nums]
268268
df = DataFrame(OrderedDict(zip(expected, [[0]] * nitems)))
269269
assert expected == list(df.columns)
270270

pandas/tests/frame/test_query_eval.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -453,7 +453,9 @@ def test_date_query_with_non_date(self):
453453

454454
for op in ["<", ">", "<=", ">="]:
455455
with pytest.raises(TypeError):
456-
df.query("dates %s nondate" % op, parser=parser, engine=engine)
456+
df.query(
457+
"dates {op} nondate".format(op=op), parser=parser, engine=engine
458+
)
457459

458460
def test_query_syntax_error(self):
459461
engine, parser = self.engine, self.parser
@@ -688,7 +690,7 @@ def test_inf(self):
688690
ops = "==", "!="
689691
d = dict(zip(ops, (operator.eq, operator.ne)))
690692
for op, f in d.items():
691-
q = "a %s inf" % op
693+
q = "a {op} inf".format(op=op)
692694
expected = df[f(df.a, np.inf)]
693695
result = df.query(q, engine=self.engine, parser=self.parser)
694696
assert_frame_equal(result, expected)

pandas/tests/frame/test_repr_info.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ def test_info_shows_column_dtypes(self):
285285
df.info(buf=buf)
286286
res = buf.getvalue()
287287
for i, dtype in enumerate(dtypes):
288-
name = "%d %d non-null %s" % (i, n, dtype)
288+
name = "{i:d} {n:d} non-null {dtype}".format(i=i, n=n, dtype=dtype)
289289
assert name in res
290290

291291
def test_info_max_cols(self):

pandas/tests/frame/test_timeseries.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ def test_frame_append_datetime64_col_other_units(self):
223223
ns_dtype = np.dtype("M8[ns]")
224224

225225
for unit in units:
226-
dtype = np.dtype("M8[%s]" % unit)
226+
dtype = np.dtype("M8[{unit}]".format(unit=unit))
227227
vals = np.arange(n, dtype=np.int64).view(dtype)
228228

229229
df = DataFrame({"ints": np.arange(n)}, index=np.arange(n))
@@ -239,7 +239,7 @@ def test_frame_append_datetime64_col_other_units(self):
239239
df["dates"] = np.arange(n, dtype=np.int64).view(ns_dtype)
240240

241241
for unit in units:
242-
dtype = np.dtype("M8[%s]" % unit)
242+
dtype = np.dtype("M8[{unit}]".format(unit=unit))
243243
vals = np.arange(n, dtype=np.int64).view(dtype)
244244

245245
tmp = df.copy()

pandas/tests/frame/test_to_csv.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -718,7 +718,7 @@ def test_to_csv_withcommas(self):
718718

719719
def test_to_csv_mixed(self):
720720
def create_cols(name):
721-
return ["%s%03d" % (name, i) for i in range(5)]
721+
return ["{name}{i:03d}".format(name=name, i=i) for i in range(5)]
722722

723723
df_float = DataFrame(
724724
np.random.randn(100, 5), dtype="float64", columns=create_cols("float")

pandas/tests/groupby/aggregate/test_other.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,8 @@ def test_agg_timezone_round_trip():
473473
assert result3 == ts
474474

475475
dates = [
476-
pd.Timestamp("2016-01-0%d 12:00:00" % i, tz="US/Pacific") for i in range(1, 5)
476+
pd.Timestamp("2016-01-0{i:d} 12:00:00".format(i=i), tz="US/Pacific")
477+
for i in range(1, 5)
477478
]
478479
df = pd.DataFrame({"A": ["a", "b"] * 2, "B": dates})
479480
grouped = df.groupby("A")

pandas/tests/groupby/test_apply.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ def desc3(group):
265265
result = group.describe()
266266

267267
# names are different
268-
result.index.name = "stat_%d" % len(group)
268+
result.index.name = "stat_{:d}".format(len(group))
269269

270270
result = result[: len(group)]
271271
# weirdo

pandas/tests/groupby/test_bin_groupby.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def _check(dtype):
9595
counts = np.zeros(len(out), dtype=np.int64)
9696
labels = ensure_int64(np.repeat(np.arange(3), np.diff(np.r_[0, bins])))
9797

98-
func = getattr(groupby, "group_ohlc_%s" % dtype)
98+
func = getattr(groupby, "group_ohlc_{dtype}".format(dtype=dtype))
9999
func(out, counts, obj[:, None], labels)
100100

101101
def _ohlc(group):

pandas/tests/groupby/test_counting.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,11 @@ def test_ngroup_respects_groupby_order(self):
197197
@pytest.mark.parametrize(
198198
"datetimelike",
199199
[
200-
[Timestamp("2016-05-%02d 20:09:25+00:00" % i) for i in range(1, 4)],
201-
[Timestamp("2016-05-%02d 20:09:25" % i) for i in range(1, 4)],
200+
[
201+
Timestamp("2016-05-{i:02d} 20:09:25+00:00".format(i=i))
202+
for i in range(1, 4)
203+
],
204+
[Timestamp("2016-05-{i:02d} 20:09:25".format(i=i)) for i in range(1, 4)],
202205
[Timedelta(x, unit="h") for x in range(1, 4)],
203206
[Period(freq="2W", year=2017, month=x) for x in range(1, 4)],
204207
],

pandas/tests/indexes/datetimelike.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,15 @@ def test_str(self):
3636
# test the string repr
3737
idx = self.create_index()
3838
idx.name = "foo"
39-
assert not "length=%s" % len(idx) in str(idx)
39+
assert not "length={}".format(len(idx)) in str(idx)
4040
assert "'foo'" in str(idx)
4141
assert idx.__class__.__name__ in str(idx)
4242

4343
if hasattr(idx, "tz"):
4444
if idx.tz is not None:
4545
assert idx.tz in str(idx)
4646
if hasattr(idx, "freq"):
47-
assert "freq='%s'" % idx.freqstr in str(idx)
47+
assert "freq='{idx.freqstr}'".format(idx=idx) in str(idx)
4848

4949
def test_view(self):
5050
i = self.create_index()

pandas/tests/indexes/datetimes/test_datetime.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def test_week_of_month_frequency(self):
9090
def test_hash_error(self):
9191
index = date_range("20010101", periods=10)
9292
with pytest.raises(
93-
TypeError, match=("unhashable type: %r" % type(index).__name__)
93+
TypeError, match=("unhashable type: {0.__name__!r}".format(type(index)))
9494
):
9595
hash(index)
9696

pandas/tests/indexes/multi/test_integrity.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,9 @@ def test_rangeindex_fallback_coercion_bug():
253253

254254
def test_hash_error(indices):
255255
index = indices
256-
with pytest.raises(TypeError, match=("unhashable type: %r" % type(index).__name__)):
256+
with pytest.raises(
257+
TypeError, match=("unhashable type: {0.__name__!r}".format(type(index)))
258+
):
257259
hash(indices)
258260

259261

pandas/tests/indexes/period/test_construction.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,7 @@ def test_constructor_year_and_quarter(self):
363363
year = pd.Series([2001, 2002, 2003])
364364
quarter = year - 2000
365365
idx = PeriodIndex(year=year, quarter=quarter)
366-
strs = ["%dQ%d" % t for t in zip(quarter, year)]
366+
strs = ["{t[0]:d}Q{t[1]:d}".format(t=t) for t in zip(quarter, year)]
367367
lops = list(map(Period, strs))
368368
p = PeriodIndex(lops)
369369
tm.assert_index_equal(p, idx)

pandas/tests/indexes/period/test_tools.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def test_dti_to_period(self):
161161
@pytest.mark.parametrize("month", MONTHS)
162162
def test_to_period_quarterly(self, month):
163163
# make sure we can make the round trip
164-
freq = "Q-%s" % month
164+
freq = "Q-{month}".format(month=month)
165165
rng = period_range("1989Q3", "1991Q3", freq=freq)
166166
stamps = rng.to_timestamp()
167167
result = stamps.to_period(freq)

pandas/tests/indexes/test_common.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ def test_dtype_str(self, indices):
163163
def test_hash_error(self, indices):
164164
index = indices
165165
with pytest.raises(
166-
TypeError, match=("unhashable type: %r" % type(index).__name__)
166+
TypeError, match=("unhashable type: {0.__name__!r}".format(type(index)))
167167
):
168168
hash(indices)
169169

pandas/tests/indexes/timedeltas/test_timedelta.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ def test_pickle(self):
239239
def test_hash_error(self):
240240
index = timedelta_range("1 days", periods=10)
241241
with pytest.raises(
242-
TypeError, match=("unhashable type: %r" % type(index).__name__)
242+
TypeError, match=("unhashable type: {0.__name__!r}".format(type(index)))
243243
):
244244
hash(index)
245245

pandas/tests/indexing/common.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717

1818
def _mklbl(prefix, n):
19-
return ["%s%s" % (prefix, i) for i in range(n)]
19+
return ["{prefix}{i}".format(prefix=prefix, i=i) for i in range(n)]
2020

2121

2222
def _axify(obj, key, axis):
@@ -105,7 +105,7 @@ def setup_method(self, method):
105105

106106
d = dict()
107107
for t in self._typs:
108-
d[t] = getattr(self, "%s_%s" % (o, t), None)
108+
d[t] = getattr(self, "{o}_{t}".format(o=o, t=t), None)
109109

110110
setattr(self, o, d)
111111

@@ -247,7 +247,7 @@ def _print(result, error=None):
247247
# if we are in fails, the ok, otherwise raise it
248248
if fails is not None:
249249
if isinstance(detail, fails):
250-
result = "ok (%s)" % type(detail).__name__
250+
result = "ok ({0.__name__})".format(type(detail))
251251
_print(result)
252252
return
253253

pandas/tests/indexing/test_iloc.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -729,7 +729,9 @@ def test_iloc_mask(self):
729729
r = expected.get(key)
730730
if r != ans:
731731
raise AssertionError(
732-
"[%s] does not match [%s], received [%s]" % (key, ans, r)
732+
"[{key}] does not match [{ans}], received [{r}]".format(
733+
key=key, ans=ans, r=r
734+
)
733735
)
734736

735737
def test_iloc_non_unique_indexing(self):

pandas/tests/indexing/test_ix.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -292,8 +292,8 @@ def test_ix_slicing_strings(self):
292292
def test_ix_setitem_out_of_bounds_axis_0(self):
293293
df = DataFrame(
294294
np.random.randn(2, 5),
295-
index=["row%s" % i for i in range(2)],
296-
columns=["col%s" % i for i in range(5)],
295+
index=["row{i}".format(i=i) for i in range(2)],
296+
columns=["col{i}".format(i=i) for i in range(5)],
297297
)
298298
with catch_warnings(record=True):
299299
msg = "cannot set by positional indexing with enlargement"
@@ -303,8 +303,8 @@ def test_ix_setitem_out_of_bounds_axis_0(self):
303303
def test_ix_setitem_out_of_bounds_axis_1(self):
304304
df = DataFrame(
305305
np.random.randn(5, 2),
306-
index=["row%s" % i for i in range(5)],
307-
columns=["col%s" % i for i in range(2)],
306+
index=["row{i}".format(i=i) for i in range(5)],
307+
columns=["col{i}".format(i=i) for i in range(2)],
308308
)
309309
with catch_warnings(record=True):
310310
msg = "cannot set by positional indexing with enlargement"

pandas/tests/internals/test_internals.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,9 @@ def create_block(typestr, placement, item_shape=None, num_offset=0):
110110
elif typestr in ("complex", "c16", "c8"):
111111
values = 1.0j * (mat.astype(typestr) + num_offset)
112112
elif typestr in ("object", "string", "O"):
113-
values = np.reshape(["A%d" % i for i in mat.ravel() + num_offset], shape)
113+
values = np.reshape(
114+
["A{i:d}".format(i=i) for i in mat.ravel() + num_offset], shape
115+
)
114116
elif typestr in ("b", "bool"):
115117
values = np.ones(shape, dtype=np.bool_)
116118
elif typestr in ("datetime", "dt", "M8[ns]"):

pandas/tests/io/excel/test_readers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,7 @@ def test_read_from_file_url(self, read_ext, datapath):
537537
# fails on some systems
538538
import platform
539539

540-
pytest.skip("failing on %s" % " ".join(platform.uname()).strip())
540+
pytest.skip("failing on {}".format(" ".join(platform.uname()).strip()))
541541

542542
tm.assert_frame_equal(url_table, local_table)
543543

pandas/tests/io/excel/test_style.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def custom_converter(css):
108108
for col1, col2 in zip(wb["frame"].columns, wb["styled"].columns):
109109
assert len(col1) == len(col2)
110110
for cell1, cell2 in zip(col1, col2):
111-
ref = "%s%d" % (cell2.column, cell2.row)
111+
ref = "{cell2.column}{cell2.row:d}".format(cell2=cell2)
112112
# XXX: this isn't as strong a test as ideal; we should
113113
# confirm that differences are exclusive
114114
if ref == "B2":
@@ -156,7 +156,7 @@ def custom_converter(css):
156156
for col1, col2 in zip(wb["frame"].columns, wb["custom"].columns):
157157
assert len(col1) == len(col2)
158158
for cell1, cell2 in zip(col1, col2):
159-
ref = "%s%d" % (cell2.column, cell2.row)
159+
ref = "{cell2.column}{cell2.row:d}".format(cell2=cell2)
160160
if ref in ("B2", "C3", "D4", "B5", "C6", "D7", "B8", "B9"):
161161
assert not cell1.font.bold
162162
assert cell2.font.bold

pandas/tests/io/formats/test_style.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ def color_negative_red(val):
362362
strings, black otherwise.
363363
"""
364364
color = "red" if val < 0 else "black"
365-
return "color: %s" % color
365+
return "color: {color}".format(color=color)
366366

367367
dic = {
368368
("a", "d"): [-1.12, 2.11],

0 commit comments

Comments
 (0)