Skip to content

CLN: 29547 replace old string formatting 4 #31963

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
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
12 changes: 5 additions & 7 deletions pandas/tests/internals/test_internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,17 +91,15 @@ 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{i:d}".format(i=i) for i in mat.ravel() + num_offset], shape
)
values = np.reshape([f"A{i:d}" 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]"):
values = (mat * 1e9).astype("M8[ns]")
elif typestr.startswith("M8[ns"):
# datetime with tz
m = re.search(r"M8\[ns,\s*(\w+\/?\w*)\]", typestr)
assert m is not None, "incompatible typestr -> {0}".format(typestr)
assert m is not None, f"incompatible typestr -> {typestr}"
tz = m.groups()[0]
assert num_items == 1, "must have only 1 num items for a tz-aware"
values = DatetimeIndex(np.arange(N) * 1e9, tz=tz)
Expand Down Expand Up @@ -607,9 +605,9 @@ def test_interleave(self):

# self
for dtype in ["f8", "i8", "object", "bool", "complex", "M8[ns]", "m8[ns]"]:
mgr = create_mgr("a: {0}".format(dtype))
mgr = create_mgr(f"a: {dtype}")
assert mgr.as_array().dtype == dtype
mgr = create_mgr("a: {0}; b: {0}".format(dtype))
mgr = create_mgr(f"a: {dtype}; b: {dtype}")
assert mgr.as_array().dtype == dtype

# will be converted according the actual dtype of the underlying
Expand Down Expand Up @@ -1136,7 +1134,7 @@ def __array__(self):
return np.array(self.value, dtype=self.dtype)

def __str__(self) -> str:
return "DummyElement({}, {})".format(self.value, self.dtype)
return f"DummyElement({self.value}, {self.dtype})"

def __repr__(self) -> str:
return str(self)
Expand Down
5 changes: 3 additions & 2 deletions pandas/tests/io/excel/test_readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,8 @@ def test_read_from_file_url(self, read_ext, datapath):
# fails on some systems
import platform

pytest.skip("failing on {}".format(" ".join(platform.uname()).strip()))
platform_info = " ".join(platform.uname()).strip()
pytest.skip(f"failing on {platform_info}")

tm.assert_frame_equal(url_table, local_table)

Expand Down Expand Up @@ -957,7 +958,7 @@ def test_excel_passes_na_filter(self, read_ext, na_filter):
def test_unexpected_kwargs_raises(self, read_ext, arg):
# gh-17964
kwarg = {arg: "Sheet1"}
msg = r"unexpected keyword argument `{}`".format(arg)
msg = fr"unexpected keyword argument `{arg}`"

with pd.ExcelFile("test1" + read_ext) as excel:
with pytest.raises(TypeError, match=msg):
Expand Down
9 changes: 3 additions & 6 deletions pandas/tests/io/excel/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,7 @@ def style(df):
def assert_equal_style(cell1, cell2, engine):
if engine in ["xlsxwriter", "openpyxl"]:
pytest.xfail(
reason=(
"GH25351: failing on some attribute "
"comparisons in {}".format(engine)
)
reason=(f"GH25351: failing on some attribute comparisons in {engine}")
)
# XXX: should find a better way to check equality
assert cell1.alignment.__dict__ == cell2.alignment.__dict__
Expand Down Expand Up @@ -108,7 +105,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 = "{cell2.column}{cell2.row:d}".format(cell2=cell2)
ref = f"{cell2.column}{cell2.row:d}"
# 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 +153,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 = "{cell2.column}{cell2.row:d}".format(cell2=cell2)
ref = f"{cell2.column}{cell2.row:d}"
if ref in ("B2", "C3", "D4", "B5", "C6", "D7", "B8", "B9"):
assert not cell1.font.bold
assert cell2.font.bold
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/io/excel/test_writers.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def set_engine(engine, ext):
which engine should be used to write Excel files. After executing
the test it rolls back said change to the global option.
"""
option_name = "io.excel.{ext}.writer".format(ext=ext.strip("."))
option_name = f"io.excel.{ext.strip('.')}.writer"
prev_engine = get_option(option_name)
set_option(option_name, engine)
yield
Expand Down Expand Up @@ -1206,15 +1206,15 @@ def test_path_path_lib(self, engine, ext):
writer = partial(df.to_excel, engine=engine)

reader = partial(pd.read_excel, index_col=0)
result = tm.round_trip_pathlib(writer, reader, path="foo.{ext}".format(ext=ext))
result = tm.round_trip_pathlib(writer, reader, path=f"foo.{ext}")
tm.assert_frame_equal(result, df)

def test_path_local_path(self, engine, ext):
df = tm.makeDataFrame()
writer = partial(df.to_excel, engine=engine)

reader = partial(pd.read_excel, index_col=0)
result = tm.round_trip_pathlib(writer, reader, path="foo.{ext}".format(ext=ext))
result = tm.round_trip_pathlib(writer, reader, path=f"foo.{ext}")
tm.assert_frame_equal(result, df)

def test_merged_cell_custom_objects(self, merge_cells, path):
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/io/excel/test_xlrd.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def test_read_xlrd_book(read_ext, frame):

# TODO: test for openpyxl as well
def test_excel_table_sheet_by_index(datapath, read_ext):
path = datapath("io", "data", "excel", "test1{}".format(read_ext))
path = datapath("io", "data", "excel", f"test1{read_ext}")
with pd.ExcelFile(path) as excel:
with pytest.raises(xlrd.XLRDError):
pd.read_excel(excel, "asdf")
4 changes: 2 additions & 2 deletions pandas/tests/io/formats/test_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ def test_detect_console_encoding_from_stdout_stdin(monkeypatch, empty, filled):
# they have values filled.
# GH 21552
with monkeypatch.context() as context:
context.setattr("sys.{}".format(empty), MockEncoding(""))
context.setattr("sys.{}".format(filled), MockEncoding(filled))
context.setattr(f"sys.{empty}", MockEncoding(""))
context.setattr(f"sys.{filled}", MockEncoding(filled))
assert detect_console_encoding() == filled


Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/io/formats/test_to_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ def test_to_html_border(option, result, expected):
else:
with option_context("display.html.border", option):
result = result(df)
expected = 'border="{}"'.format(expected)
expected = f'border="{expected}"'
assert expected in result


Expand All @@ -318,7 +318,7 @@ def test_to_html(biggie_df_fixture):
assert isinstance(s, str)

df.to_html(columns=["B", "A"], col_space=17)
df.to_html(columns=["B", "A"], formatters={"A": lambda x: "{x:.1f}".format(x=x)})
df.to_html(columns=["B", "A"], formatters={"A": lambda x: f"{x:.1f}"})

df.to_html(columns=["B", "A"], float_format=str)
df.to_html(columns=["B", "A"], col_space=12, float_format=str)
Expand Down Expand Up @@ -745,7 +745,7 @@ def test_to_html_with_col_space_units(unit):
if isinstance(unit, int):
unit = str(unit) + "px"
for h in hdrs:
expected = '<th style="min-width: {unit};">'.format(unit=unit)
expected = f'<th style="min-width: {unit};">'
assert expected in h


Expand Down
12 changes: 5 additions & 7 deletions pandas/tests/io/formats/test_to_latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,10 @@ def test_to_latex_with_formatters(self):

formatters = {
"datetime64": lambda x: x.strftime("%Y-%m"),
"float": lambda x: "[{x: 4.1f}]".format(x=x),
"int": lambda x: "0x{x:x}".format(x=x),
"object": lambda x: "-{x!s}-".format(x=x),
"__index__": lambda x: "index: {x}".format(x=x),
"float": lambda x: f"[{x: 4.1f}]",
"int": lambda x: f"0x{x:x}",
"object": lambda x: f"-{x!s}-",
"__index__": lambda x: f"index: {x}",
}
result = df.to_latex(formatters=dict(formatters))

Expand Down Expand Up @@ -744,9 +744,7 @@ def test_to_latex_multiindex_names(self, name0, name1, axes):

idx_names = tuple(n or "{}" for n in names)
idx_names_row = (
"{idx_names[0]} & {idx_names[1]} & & & & \\\\\n".format(
idx_names=idx_names
)
f"{idx_names[0]} & {idx_names[1]} & & & & \\\\\n"
if (0 in axes and any(names))
else ""
)
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/io/generate_legacy_storage_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,17 +323,17 @@ def write_legacy_pickles(output_dir):
"This script generates a storage file for the current arch, system, "
"and python version"
)
print(" pandas version: {0}".format(version))
print(" output dir : {0}".format(output_dir))
print(f" pandas version: {version}")
print(f" output dir : {output_dir}")
print(" storage format: pickle")

pth = "{0}.pickle".format(platform_name())
pth = f"{platform_name()}.pickle"

fh = open(os.path.join(output_dir, pth), "wb")
pickle.dump(create_pickle_data(), fh, pickle.HIGHEST_PROTOCOL)
fh.close()

print("created pickle file: {pth}".format(pth=pth))
print(f"created pickle file: {pth}")


def write_legacy_file():
Expand Down