Skip to content

TST/CLN: replace %s formatting syntax with .format in tests #27324

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 1 commit into from
Jul 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
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
10 changes: 6 additions & 4 deletions pandas/tests/arrays/categorical/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,20 +92,22 @@ def test_codes_dtypes(self):
result = Categorical(["foo", "bar", "baz"])
assert result.codes.dtype == "int8"

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

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

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

# removing cats
result = result.remove_categories(["foo%05d" % i for i in range(300)])
result = result.remove_categories(
["foo{i:05d}".format(i=i) for i in range(300)]
)
assert result.codes.dtype == "int8"

@pytest.mark.parametrize("ordered", [True, False])
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/arrays/sparse/test_libsparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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_%s_float64" % opname)
sparse_op = getattr(splib, "sparse_{opname}_float64".format(opname=opname))
python_op = getattr(operator, opname)
self._op_tests(sparse_op, python_op)
6 changes: 3 additions & 3 deletions pandas/tests/computation/test_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -736,16 +736,16 @@ def test_float_truncation(self):

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

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

exact = 1000000000.0011
result = df.query("A == %.4f" % exact)
result = df.query("A == {exact:.4f}".format(exact=exact))
expected = df.loc[[1], :]
tm.assert_frame_equal(expected, result)

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/dtypes/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -1349,7 +1349,7 @@ def test_is_scalar_pandas_containers(self):

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


Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/frame/test_alter_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ def __init__(self, name, color):
self.color = color

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

# necessary for pretty KeyError
__repr__ = __str__
Expand Down Expand Up @@ -419,7 +419,7 @@ def __init__(self, name, color):
self.color = color

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

thing1 = Thing("One", "red")
thing2 = Thing("Two", "blue")
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/frame/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,19 @@ def test_get_value(self, float_frame):

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

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

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

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

def test_get_axis(self, float_frame):
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ def test_constructor_ordereddict(self):
nitems = 100
nums = list(range(nitems))
random.shuffle(nums)
expected = ["A%d" % i for i in nums]
expected = ["A{i:d}".format(i=i) for i in nums]
df = DataFrame(OrderedDict(zip(expected, [[0]] * nitems)))
assert expected == list(df.columns)

Expand Down
6 changes: 4 additions & 2 deletions pandas/tests/frame/test_query_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,9 @@ def test_date_query_with_non_date(self):

for op in ["<", ">", "<=", ">="]:
with pytest.raises(TypeError):
df.query("dates %s nondate" % op, parser=parser, engine=engine)
df.query(
"dates {op} nondate".format(op=op), parser=parser, engine=engine
)

def test_query_syntax_error(self):
engine, parser = self.engine, self.parser
Expand Down Expand Up @@ -688,7 +690,7 @@ def test_inf(self):
ops = "==", "!="
d = dict(zip(ops, (operator.eq, operator.ne)))
for op, f in d.items():
q = "a %s inf" % op
q = "a {op} inf".format(op=op)
expected = df[f(df.a, np.inf)]
result = df.query(q, engine=self.engine, parser=self.parser)
assert_frame_equal(result, expected)
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/frame/test_repr_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def test_info_shows_column_dtypes(self):
df.info(buf=buf)
res = buf.getvalue()
for i, dtype in enumerate(dtypes):
name = "%d %d non-null %s" % (i, n, dtype)
name = "{i:d} {n:d} non-null {dtype}".format(i=i, n=n, dtype=dtype)
assert name in res

def test_info_max_cols(self):
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/frame/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def test_frame_append_datetime64_col_other_units(self):
ns_dtype = np.dtype("M8[ns]")

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

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

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

tmp = df.copy()
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/frame/test_to_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,7 @@ def test_to_csv_withcommas(self):

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

df_float = DataFrame(
np.random.randn(100, 5), dtype="float64", columns=create_cols("float")
Expand Down
3 changes: 2 additions & 1 deletion pandas/tests/groupby/aggregate/test_other.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,8 @@ def test_agg_timezone_round_trip():
assert result3 == ts

dates = [
pd.Timestamp("2016-01-0%d 12:00:00" % i, tz="US/Pacific") for i in range(1, 5)
pd.Timestamp("2016-01-0{i:d} 12:00:00".format(i=i), tz="US/Pacific")
for i in range(1, 5)
]
df = pd.DataFrame({"A": ["a", "b"] * 2, "B": dates})
grouped = df.groupby("A")
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ def desc3(group):
result = group.describe()

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

result = result[: len(group)]
# weirdo
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/groupby/test_bin_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def _check(dtype):
counts = np.zeros(len(out), dtype=np.int64)
labels = ensure_int64(np.repeat(np.arange(3), np.diff(np.r_[0, bins])))

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

def _ohlc(group):
Expand Down
7 changes: 5 additions & 2 deletions pandas/tests/groupby/test_counting.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,11 @@ def test_ngroup_respects_groupby_order(self):
@pytest.mark.parametrize(
"datetimelike",
[
[Timestamp("2016-05-%02d 20:09:25+00:00" % i) for i in range(1, 4)],
[Timestamp("2016-05-%02d 20:09:25" % i) for i in range(1, 4)],
[
Timestamp("2016-05-{i:02d} 20:09:25+00:00".format(i=i))
for i in range(1, 4)
],
[Timestamp("2016-05-{i:02d} 20:09:25".format(i=i)) for i in range(1, 4)],
[Timedelta(x, unit="h") for x in range(1, 4)],
[Period(freq="2W", year=2017, month=x) for x in range(1, 4)],
],
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ def test_str(self):
# test the string repr
idx = self.create_index()
idx.name = "foo"
assert not "length=%s" % len(idx) in str(idx)
assert not "length={}".format(len(idx)) in str(idx)
assert "'foo'" in str(idx)
assert idx.__class__.__name__ in str(idx)

if hasattr(idx, "tz"):
if idx.tz is not None:
assert idx.tz in str(idx)
if hasattr(idx, "freq"):
assert "freq='%s'" % idx.freqstr in str(idx)
assert "freq='{idx.freqstr}'".format(idx=idx) in str(idx)

def test_view(self):
i = self.create_index()
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/datetimes/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def test_week_of_month_frequency(self):
def test_hash_error(self):
index = date_range("20010101", periods=10)
with pytest.raises(
TypeError, match=("unhashable type: %r" % type(index).__name__)
TypeError, match=("unhashable type: {0.__name__!r}".format(type(index)))
):
hash(index)

Expand Down
4 changes: 3 additions & 1 deletion pandas/tests/indexes/multi/test_integrity.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,9 @@ def test_rangeindex_fallback_coercion_bug():

def test_hash_error(indices):
index = indices
with pytest.raises(TypeError, match=("unhashable type: %r" % type(index).__name__)):
with pytest.raises(
TypeError, match=("unhashable type: {0.__name__!r}".format(type(index)))
):
hash(indices)


Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/period/test_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ def test_constructor_year_and_quarter(self):
year = pd.Series([2001, 2002, 2003])
quarter = year - 2000
idx = PeriodIndex(year=year, quarter=quarter)
strs = ["%dQ%d" % t for t in zip(quarter, year)]
strs = ["{t[0]:d}Q{t[1]:d}".format(t=t) for t in zip(quarter, year)]
lops = list(map(Period, strs))
p = PeriodIndex(lops)
tm.assert_index_equal(p, idx)
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/period/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def test_dti_to_period(self):
@pytest.mark.parametrize("month", MONTHS)
def test_to_period_quarterly(self, month):
# make sure we can make the round trip
freq = "Q-%s" % month
freq = "Q-{month}".format(month=month)
rng = period_range("1989Q3", "1991Q3", freq=freq)
stamps = rng.to_timestamp()
result = stamps.to_period(freq)
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def test_dtype_str(self, indices):
def test_hash_error(self, indices):
index = indices
with pytest.raises(
TypeError, match=("unhashable type: %r" % type(index).__name__)
TypeError, match=("unhashable type: {0.__name__!r}".format(type(index)))
):
hash(indices)

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/timedeltas/test_timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def test_pickle(self):
def test_hash_error(self):
index = timedelta_range("1 days", periods=10)
with pytest.raises(
TypeError, match=("unhashable type: %r" % type(index).__name__)
TypeError, match=("unhashable type: {0.__name__!r}".format(type(index)))
):
hash(index)

Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/indexing/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@


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


def _axify(obj, key, axis):
Expand Down Expand Up @@ -105,7 +105,7 @@ def setup_method(self, method):

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

setattr(self, o, d)

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

Expand Down
4 changes: 3 additions & 1 deletion pandas/tests/indexing/test_iloc.py
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,9 @@ def test_iloc_mask(self):
r = expected.get(key)
if r != ans:
raise AssertionError(
"[%s] does not match [%s], received [%s]" % (key, ans, r)
"[{key}] does not match [{ans}], received [{r}]".format(
key=key, ans=ans, r=r
)
)

def test_iloc_non_unique_indexing(self):
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/indexing/test_ix.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,8 +292,8 @@ def test_ix_slicing_strings(self):
def test_ix_setitem_out_of_bounds_axis_0(self):
df = DataFrame(
np.random.randn(2, 5),
index=["row%s" % i for i in range(2)],
columns=["col%s" % i for i in range(5)],
index=["row{i}".format(i=i) for i in range(2)],
columns=["col{i}".format(i=i) for i in range(5)],
)
with catch_warnings(record=True):
msg = "cannot set by positional indexing with enlargement"
Expand All @@ -303,8 +303,8 @@ def test_ix_setitem_out_of_bounds_axis_0(self):
def test_ix_setitem_out_of_bounds_axis_1(self):
df = DataFrame(
np.random.randn(5, 2),
index=["row%s" % i for i in range(5)],
columns=["col%s" % i for i in range(2)],
index=["row{i}".format(i=i) for i in range(5)],
columns=["col{i}".format(i=i) for i in range(2)],
)
with catch_warnings(record=True):
msg = "cannot set by positional indexing with enlargement"
Expand Down
4 changes: 3 additions & 1 deletion pandas/tests/internals/test_internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ def create_block(typestr, placement, item_shape=None, num_offset=0):
elif typestr in ("complex", "c16", "c8"):
values = 1.0j * (mat.astype(typestr) + num_offset)
elif typestr in ("object", "string", "O"):
values = np.reshape(["A%d" % i for i in mat.ravel() + num_offset], shape)
values = np.reshape(
["A{i:d}".format(i=i) for i in mat.ravel() + num_offset], shape
)
elif typestr in ("b", "bool"):
values = np.ones(shape, dtype=np.bool_)
elif typestr in ("datetime", "dt", "M8[ns]"):
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/io/excel/test_readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ def test_read_from_file_url(self, read_ext, datapath):
# fails on some systems
import platform

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

tm.assert_frame_equal(url_table, local_table)

Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/io/excel/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def custom_converter(css):
for col1, col2 in zip(wb["frame"].columns, wb["styled"].columns):
assert len(col1) == len(col2)
for cell1, cell2 in zip(col1, col2):
ref = "%s%d" % (cell2.column, cell2.row)
ref = "{cell2.column}{cell2.row:d}".format(cell2=cell2)
# XXX: this isn't as strong a test as ideal; we should
# confirm that differences are exclusive
if ref == "B2":
Expand Down Expand Up @@ -156,7 +156,7 @@ def custom_converter(css):
for col1, col2 in zip(wb["frame"].columns, wb["custom"].columns):
assert len(col1) == len(col2)
for cell1, cell2 in zip(col1, col2):
ref = "%s%d" % (cell2.column, cell2.row)
ref = "{cell2.column}{cell2.row:d}".format(cell2=cell2)
if ref in ("B2", "C3", "D4", "B5", "C6", "D7", "B8", "B9"):
assert not cell1.font.bold
assert cell2.font.bold
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/io/formats/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ def color_negative_red(val):
strings, black otherwise.
"""
color = "red" if val < 0 else "black"
return "color: %s" % color
return "color: {color}".format(color=color)

dic = {
("a", "d"): [-1.12, 2.11],
Expand Down
Loading