Skip to content

CLN: replacing '.format' with f-strings in various files #30706

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 8 commits into from
Jan 6, 2020
Merged
Show file tree
Hide file tree
Changes from 5 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
16 changes: 6 additions & 10 deletions pandas/tests/util/test_validate_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,8 @@ def test_bad_arg_length_max_value_single():
max_length = len(compat_args) + min_fname_arg_count
actual_length = len(args) + min_fname_arg_count
msg = (
r"{fname}\(\) takes at most {max_length} "
r"argument \({actual_length} given\)".format(
fname=_fname, max_length=max_length, actual_length=actual_length
)
fr"{_fname}\(\) takes at most {max_length} "
fr"argument \({actual_length} given\)"
)

with pytest.raises(TypeError, match=msg):
Expand All @@ -38,10 +36,8 @@ def test_bad_arg_length_max_value_multiple():
max_length = len(compat_args) + min_fname_arg_count
actual_length = len(args) + min_fname_arg_count
msg = (
r"{fname}\(\) takes at most {max_length} "
r"arguments \({actual_length} given\)".format(
fname=_fname, max_length=max_length, actual_length=actual_length
)
fr"{_fname}\(\) takes at most {max_length} "
fr"arguments \({actual_length} given\)"
)

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

compat_args = {"foo": 2, "bar": -1, "baz": 3}
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/util/test_validate_kwargs.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ def test_bad_kwarg():
def test_not_all_none(i):
bad_arg = "foo"
msg = (
r"the '{arg}' parameter is not supported "
r"in the pandas implementation of {func}\(\)".format(arg=bad_arg, func=_fname)
fr"the '{bad_arg}' parameter is not supported "
fr"in the pandas implementation of {_fname}\(\)"
)

compat_args = {"foo": 1, "bar": "s", "baz": None}
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/window/test_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def test_agg_function_support(self, arg):
df = pd.DataFrame({"A": np.arange(5)})
roll = df.rolling(2, win_type="triang")

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

Expand Down
14 changes: 7 additions & 7 deletions pandas/tseries/holiday.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,16 +186,16 @@ class from pandas.tseries.offsets
def __repr__(self) -> str:
info = ""
if self.year is not None:
info += "year={year}, ".format(year=self.year)
info += "month={mon}, day={day}, ".format(mon=self.month, day=self.day)
info += f"year={self.year}, "
info += f"month={self.month}, day={self.day}, "

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

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

repr = "Holiday: {name} ({info})".format(name=self.name, info=info)
repr = f"Holiday: {self.name} ({info})"
return repr

def dates(self, start_date, end_date, return_name=False):
Expand Down Expand Up @@ -394,8 +394,8 @@ def holidays(self, start=None, end=None, return_name=False):
"""
if self.rules is None:
raise Exception(
"Holiday Calendar {name} does not have any "
"rules specified".format(name=self.name)
f"Holiday Calendar {self.name} does not have any "
f"rules specified"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

f string prefix not needed here

Suggested change
f"rules specified"
"rules specified"

)

if start is None:
Expand Down
4 changes: 2 additions & 2 deletions scripts/download_wheels.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def fetch(version):
files = [
x
for x in root.xpath("//a/text()")
if x.startswith("pandas-{}".format(version)) and not dest.joinpath(x).exists()
if x.startswith(f"pandas-{version}") and not dest.joinpath(x).exists()
]

N = len(files)
Expand All @@ -36,7 +36,7 @@ def fetch(version):
link = urllib.request.urljoin(base, filename)
urllib.request.urlretrieve(link, out)
print(
"Downloaded {link} to {out} [{i}/{N}]".format(link=link, out=out, i=i, N=N)
f"Downloaded {link} to {out} [{i}/{N}]"
)


Expand Down
8 changes: 4 additions & 4 deletions scripts/generate_pip_deps_from_conda.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,13 @@ def main(conda_fname, pip_fname, compare=False):
)
if res:
msg = (
"`requirements-dev.txt` has to be generated with `{}` after "
"`environment.yml` is modified.\n".format(sys.argv[0])
f"`requirements-dev.txt` has to be generated with `{sys.argv[0]}` after "
f"`environment.yml` is modified.\n"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your feedback, I just changed it

)
if args.azure:
msg = (
"##vso[task.logissue type=error;"
"sourcepath=requirements-dev.txt]{}".format(msg)
f"##vso[task.logissue type=error;"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same

f"sourcepath=requirements-dev.txt]{msg}"
)
sys.stderr.write(msg)
sys.exit(res)
4 changes: 2 additions & 2 deletions scripts/tests/test_validate_docstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -1300,7 +1300,7 @@ def test_resolves_class_name(self, name, expected_obj):

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

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

Expand Down
34 changes: 15 additions & 19 deletions scripts/validate_docstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ def source_file_def_line(self):
@property
def github_url(self):
url = "https://github.com/pandas-dev/pandas/blob/master/"
url += "{}#L{}".format(self.source_file_name, self.source_file_def_line)
url += f"{self.source_file_name}#L{self.source_file_def_line}"
return url

@property
Expand Down Expand Up @@ -501,7 +501,7 @@ def parameter_desc(self, param):
desc = self.doc_parameters[param][1]
# Find and strip out any sphinx directives
for directive in DIRECTIVES:
full_directive = ".. {}".format(directive)
full_directive = f".. {directive}"
if full_directive in desc:
# Only retain any description before the directive
desc = desc[: desc.index(full_directive)]
Expand Down Expand Up @@ -825,14 +825,14 @@ def get_validation_data(doc):
"EX03",
error_code=err.error_code,
error_message=err.message,
times_happening=" ({} times)".format(err.count)
times_happening=f" ({err.count} times)"
if err.count > 1
else "",
)
)
examples_source_code = "".join(doc.examples_source_code)
for wrong_import in ("numpy", "pandas"):
if "import {}".format(wrong_import) in examples_source_code:
if f"import {wrong_import}" in examples_source_code:
errs.append(error("EX04", imported_library=wrong_import))
return errs, wrns, examples_errs

Expand Down Expand Up @@ -920,7 +920,7 @@ def validate_all(prefix, ignore_deprecated=False):
api_item_names = set(list(zip(*api_items))[0])
for class_ in (pandas.Series, pandas.DataFrame):
for member in inspect.getmembers(class_):
func_name = "pandas.{}.{}".format(class_.__name__, member[0])
func_name = f"pandas.{class_.__name__}.{member[0]}"
if not member[0].startswith("_") and func_name not in api_item_names:
if prefix and not func_name.startswith(prefix):
continue
Expand All @@ -938,13 +938,9 @@ def header(title, width=80, char="#"):
full_line = char * width
side_len = (width - len(title) - 2) // 2
adj = "" if len(title) % 2 == 0 else " "
title_line = "{side} {title}{adj} {side}".format(
side=char * side_len, title=title, adj=adj
)
title_line = f"{char * side_len} {title}{adj} {side}"
Copy link
Member

@ShaharNaveh ShaharNaveh Jan 5, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace the {side} (at the very end) with {char * side_len} 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now I see, thank you.


return "\n{full_line}\n{title_line}\n{full_line}\n\n".format(
full_line=full_line, title_line=title_line
)
return f"\n{full_line}\n{title_line}\n{full_line}\n\n"

exit_status = 0
if func_name is None:
Expand Down Expand Up @@ -986,24 +982,24 @@ def header(title, width=80, char="#"):

else:
result = validate_one(func_name)
sys.stderr.write(header("Docstring ({})".format(func_name)))
sys.stderr.write("{}\n".format(result["docstring"]))
sys.stderr.write(header(f"Docstring ({func_name})"))
sys.stderr.write(f"{result['docstring']}\n")
sys.stderr.write(header("Validation"))
if result["errors"]:
sys.stderr.write("{} Errors found:\n".format(len(result["errors"])))
sys.stderr.write(f"{len(result['errors'])} Errors found:\n")
for err_code, err_desc in result["errors"]:
# Failing examples are printed at the end
if err_code == "EX02":
sys.stderr.write("\tExamples do not pass tests\n")
continue
sys.stderr.write("\t{}\n".format(err_desc))
sys.stderr.write(f"\t{err_desc}\n")
if result["warnings"]:
sys.stderr.write("{} Warnings found:\n".format(len(result["warnings"])))
sys.stderr.write(f"{len(result['warnings'])} Warnings found:\n")
for wrn_code, wrn_desc in result["warnings"]:
sys.stderr.write("\t{}\n".format(wrn_desc))
sys.stderr.write(f"\t{wrn_desc}\n")

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

if result["examples_errors"]:
sys.stderr.write(header("Doctests"))
Expand All @@ -1027,7 +1023,7 @@ def header(title, width=80, char="#"):
choices=format_opts,
help="format of the output when validating "
"multiple docstrings (ignored when validating one)."
"It can be {}".format(str(format_opts)[1:-1]),
f"It can be {str(format_opts)[1:-1]}",
)
argparser.add_argument(
"--prefix",
Expand Down