Skip to content

Commit 036dc88

Browse files
AlfredoGJjreback
authored andcommitted
CLN: replacing '.format' with f-strings in various files (#30706)
1 parent bebaff0 commit 036dc88

8 files changed

+37
-50
lines changed

pandas/tests/util/test_validate_args.py

+6-10
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,8 @@ def test_bad_arg_length_max_value_single():
2020
max_length = len(compat_args) + min_fname_arg_count
2121
actual_length = len(args) + min_fname_arg_count
2222
msg = (
23-
r"{fname}\(\) takes at most {max_length} "
24-
r"argument \({actual_length} given\)".format(
25-
fname=_fname, max_length=max_length, actual_length=actual_length
26-
)
23+
fr"{_fname}\(\) takes at most {max_length} "
24+
fr"argument \({actual_length} given\)"
2725
)
2826

2927
with pytest.raises(TypeError, match=msg):
@@ -38,10 +36,8 @@ def test_bad_arg_length_max_value_multiple():
3836
max_length = len(compat_args) + min_fname_arg_count
3937
actual_length = len(args) + min_fname_arg_count
4038
msg = (
41-
r"{fname}\(\) takes at most {max_length} "
42-
r"arguments \({actual_length} given\)".format(
43-
fname=_fname, max_length=max_length, actual_length=actual_length
44-
)
39+
fr"{_fname}\(\) takes at most {max_length} "
40+
fr"arguments \({actual_length} given\)"
4541
)
4642

4743
with pytest.raises(TypeError, match=msg):
@@ -52,8 +48,8 @@ def test_bad_arg_length_max_value_multiple():
5248
def test_not_all_defaults(i):
5349
bad_arg = "foo"
5450
msg = (
55-
"the '{arg}' parameter is not supported "
56-
r"in the pandas implementation of {func}\(\)".format(arg=bad_arg, func=_fname)
51+
f"the '{bad_arg}' parameter is not supported "
52+
fr"in the pandas implementation of {_fname}\(\)"
5753
)
5854

5955
compat_args = {"foo": 2, "bar": -1, "baz": 3}

pandas/tests/util/test_validate_kwargs.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ def test_bad_kwarg():
2222
def test_not_all_none(i):
2323
bad_arg = "foo"
2424
msg = (
25-
r"the '{arg}' parameter is not supported "
26-
r"in the pandas implementation of {func}\(\)".format(arg=bad_arg, func=_fname)
25+
fr"the '{bad_arg}' parameter is not supported "
26+
fr"in the pandas implementation of {_fname}\(\)"
2727
)
2828

2929
compat_args = {"foo": 1, "bar": "s", "baz": None}

pandas/tests/window/test_window.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def test_agg_function_support(self, arg):
6565
df = pd.DataFrame({"A": np.arange(5)})
6666
roll = df.rolling(2, win_type="triang")
6767

68-
msg = "'{arg}' is not a valid function for 'Window' object".format(arg=arg)
68+
msg = f"'{arg}' is not a valid function for 'Window' object"
6969
with pytest.raises(AttributeError, match=msg):
7070
roll.agg(arg)
7171

pandas/tseries/holiday.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -186,16 +186,16 @@ class from pandas.tseries.offsets
186186
def __repr__(self) -> str:
187187
info = ""
188188
if self.year is not None:
189-
info += "year={year}, ".format(year=self.year)
190-
info += "month={mon}, day={day}, ".format(mon=self.month, day=self.day)
189+
info += f"year={self.year}, "
190+
info += f"month={self.month}, day={self.day}, "
191191

192192
if self.offset is not None:
193-
info += "offset={offset}".format(offset=self.offset)
193+
info += f"offset={self.offset}"
194194

195195
if self.observance is not None:
196-
info += "observance={obs}".format(obs=self.observance)
196+
info += f"observance={self.observance}"
197197

198-
repr = "Holiday: {name} ({info})".format(name=self.name, info=info)
198+
repr = f"Holiday: {self.name} ({info})"
199199
return repr
200200

201201
def dates(self, start_date, end_date, return_name=False):
@@ -394,8 +394,7 @@ def holidays(self, start=None, end=None, return_name=False):
394394
"""
395395
if self.rules is None:
396396
raise Exception(
397-
"Holiday Calendar {name} does not have any "
398-
"rules specified".format(name=self.name)
397+
f"Holiday Calendar {self.name} does not have any rules specified"
399398
)
400399

401400
if start is None:

scripts/download_wheels.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def fetch(version):
2626
files = [
2727
x
2828
for x in root.xpath("//a/text()")
29-
if x.startswith("pandas-{}".format(version)) and not dest.joinpath(x).exists()
29+
if x.startswith(f"pandas-{version}") and not dest.joinpath(x).exists()
3030
]
3131

3232
N = len(files)
@@ -35,9 +35,7 @@ def fetch(version):
3535
out = str(dest.joinpath(filename))
3636
link = urllib.request.urljoin(base, filename)
3737
urllib.request.urlretrieve(link, out)
38-
print(
39-
"Downloaded {link} to {out} [{i}/{N}]".format(link=link, out=out, i=i, N=N)
40-
)
38+
print(f"Downloaded {link} to {out} [{i}/{N}]")
4139

4240

4341
def main(args=None):

scripts/generate_pip_deps_from_conda.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -127,13 +127,13 @@ def main(conda_fname, pip_fname, compare=False):
127127
)
128128
if res:
129129
msg = (
130-
"`requirements-dev.txt` has to be generated with `{}` after "
131-
"`environment.yml` is modified.\n".format(sys.argv[0])
130+
f"`requirements-dev.txt` has to be generated with `{sys.argv[0]}` after "
131+
"`environment.yml` is modified.\n"
132132
)
133133
if args.azure:
134134
msg = (
135135
"##vso[task.logissue type=error;"
136-
"sourcepath=requirements-dev.txt]{}".format(msg)
136+
f"sourcepath=requirements-dev.txt]{msg}"
137137
)
138138
sys.stderr.write(msg)
139139
sys.exit(res)

scripts/tests/test_validate_docstrings.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1300,7 +1300,7 @@ def test_resolves_class_name(self, name, expected_obj):
13001300

13011301
@pytest.mark.parametrize("invalid_name", ["panda", "panda.DataFrame"])
13021302
def test_raises_for_invalid_module_name(self, invalid_name):
1303-
msg = 'No module can be imported from "{}"'.format(invalid_name)
1303+
msg = f'No module can be imported from "{invalid_name}"'
13041304
with pytest.raises(ImportError, match=msg):
13051305
validate_docstrings.Docstring(invalid_name)
13061306

@@ -1310,7 +1310,7 @@ def test_raises_for_invalid_module_name(self, invalid_name):
13101310
def test_raises_for_invalid_attribute_name(self, invalid_name):
13111311
name_components = invalid_name.split(".")
13121312
obj_name, invalid_attr_name = name_components[-2], name_components[-1]
1313-
msg = "'{}' has no attribute '{}'".format(obj_name, invalid_attr_name)
1313+
msg = f"'{obj_name}' has no attribute '{invalid_attr_name}'"
13141314
with pytest.raises(AttributeError, match=msg):
13151315
validate_docstrings.Docstring(invalid_name)
13161316

scripts/validate_docstrings.py

+15-21
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ def source_file_def_line(self):
357357
@property
358358
def github_url(self):
359359
url = "https://github.com/pandas-dev/pandas/blob/master/"
360-
url += "{}#L{}".format(self.source_file_name, self.source_file_def_line)
360+
url += f"{self.source_file_name}#L{self.source_file_def_line}"
361361
return url
362362

363363
@property
@@ -501,7 +501,7 @@ def parameter_desc(self, param):
501501
desc = self.doc_parameters[param][1]
502502
# Find and strip out any sphinx directives
503503
for directive in DIRECTIVES:
504-
full_directive = ".. {}".format(directive)
504+
full_directive = f".. {directive}"
505505
if full_directive in desc:
506506
# Only retain any description before the directive
507507
desc = desc[: desc.index(full_directive)]
@@ -825,14 +825,12 @@ def get_validation_data(doc):
825825
"EX03",
826826
error_code=err.error_code,
827827
error_message=err.message,
828-
times_happening=" ({} times)".format(err.count)
829-
if err.count > 1
830-
else "",
828+
times_happening=f" ({err.count} times)" if err.count > 1 else "",
831829
)
832830
)
833831
examples_source_code = "".join(doc.examples_source_code)
834832
for wrong_import in ("numpy", "pandas"):
835-
if "import {}".format(wrong_import) in examples_source_code:
833+
if f"import {wrong_import}" in examples_source_code:
836834
errs.append(error("EX04", imported_library=wrong_import))
837835
return errs, wrns, examples_errs
838836

@@ -920,7 +918,7 @@ def validate_all(prefix, ignore_deprecated=False):
920918
api_item_names = set(list(zip(*api_items))[0])
921919
for class_ in (pandas.Series, pandas.DataFrame):
922920
for member in inspect.getmembers(class_):
923-
func_name = "pandas.{}.{}".format(class_.__name__, member[0])
921+
func_name = f"pandas.{class_.__name__}.{member[0]}"
924922
if not member[0].startswith("_") and func_name not in api_item_names:
925923
if prefix and not func_name.startswith(prefix):
926924
continue
@@ -938,13 +936,9 @@ def header(title, width=80, char="#"):
938936
full_line = char * width
939937
side_len = (width - len(title) - 2) // 2
940938
adj = "" if len(title) % 2 == 0 else " "
941-
title_line = "{side} {title}{adj} {side}".format(
942-
side=char * side_len, title=title, adj=adj
943-
)
939+
title_line = f"{char * side_len} {title}{adj} {char * side_len}"
944940

945-
return "\n{full_line}\n{title_line}\n{full_line}\n\n".format(
946-
full_line=full_line, title_line=title_line
947-
)
941+
return f"\n{full_line}\n{title_line}\n{full_line}\n\n"
948942

949943
exit_status = 0
950944
if func_name is None:
@@ -986,24 +980,24 @@ def header(title, width=80, char="#"):
986980

987981
else:
988982
result = validate_one(func_name)
989-
sys.stderr.write(header("Docstring ({})".format(func_name)))
990-
sys.stderr.write("{}\n".format(result["docstring"]))
983+
sys.stderr.write(header(f"Docstring ({func_name})"))
984+
sys.stderr.write(f"{result['docstring']}\n")
991985
sys.stderr.write(header("Validation"))
992986
if result["errors"]:
993-
sys.stderr.write("{} Errors found:\n".format(len(result["errors"])))
987+
sys.stderr.write(f"{len(result['errors'])} Errors found:\n")
994988
for err_code, err_desc in result["errors"]:
995989
# Failing examples are printed at the end
996990
if err_code == "EX02":
997991
sys.stderr.write("\tExamples do not pass tests\n")
998992
continue
999-
sys.stderr.write("\t{}\n".format(err_desc))
993+
sys.stderr.write(f"\t{err_desc}\n")
1000994
if result["warnings"]:
1001-
sys.stderr.write("{} Warnings found:\n".format(len(result["warnings"])))
995+
sys.stderr.write(f"{len(result['warnings'])} Warnings found:\n")
1002996
for wrn_code, wrn_desc in result["warnings"]:
1003-
sys.stderr.write("\t{}\n".format(wrn_desc))
997+
sys.stderr.write(f"\t{wrn_desc}\n")
1004998

1005999
if not result["errors"]:
1006-
sys.stderr.write('Docstring for "{}" correct. :)\n'.format(func_name))
1000+
sys.stderr.write(f'Docstring for "{func_name}" correct. :)\n')
10071001

10081002
if result["examples_errors"]:
10091003
sys.stderr.write(header("Doctests"))
@@ -1027,7 +1021,7 @@ def header(title, width=80, char="#"):
10271021
choices=format_opts,
10281022
help="format of the output when validating "
10291023
"multiple docstrings (ignored when validating one)."
1030-
"It can be {}".format(str(format_opts)[1:-1]),
1024+
f"It can be {str(format_opts)[1:-1]}",
10311025
)
10321026
argparser.add_argument(
10331027
"--prefix",

0 commit comments

Comments
 (0)