Skip to content
This repository has been archived by the owner on Jan 13, 2024. It is now read-only.

Commit

Permalink
Uses f strings
Browse files Browse the repository at this point in the history
  • Loading branch information
sdpython committed Jul 19, 2022
1 parent b705aec commit f00370b
Show file tree
Hide file tree
Showing 62 changed files with 275 additions and 308 deletions.
14 changes: 7 additions & 7 deletions _doc/competitions/2016_ENSAE_2A/competition/program/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def main_codalab_wrapper(fct, metric_name, argv, truth_file="truth.txt", submiss
truth_dir = os.path.join(input_dir, 'ref')

if not os.path.isdir(submit_dir):
raise FileNotFoundError("%s doesn't exist" % submit_dir)
raise FileNotFoundError(f"{submit_dir} doesn't exist")

if os.path.isdir(submit_dir) and os.path.isdir(truth_dir):
if not os.path.exists(output_dir):
Expand All @@ -34,7 +34,7 @@ def main_codalab_wrapper(fct, metric_name, argv, truth_file="truth.txt", submiss
output=os.path.join(output_dir, output_file))
else:
raise FileNotFoundError(
"{0} or {1} is not a folder".format(submit_dir, truth_dir))
f"{submit_dir} or {truth_dir} is not a folder")


def private_codalab_wrapper(fct, metric_name, fold1, fold2, f1="answer.txt", f2="answer.txt", output="scores.txt"):
Expand All @@ -56,12 +56,12 @@ def private_codalab_wrapper(fct, metric_name, fold1, fold2, f1="answer.txt", f2=
f1 = os.path.join(fold1, f1)
f2 = os.path.join(fold2, f2)
if not os.path.exists(f1):
raise FileNotFoundError("unable to find '{0}'".format(f1))
raise FileNotFoundError(f"unable to find '{f1}'")
if not os.path.exists(f2):
raise FileNotFoundError("unable to find '{0}'".format(f2))
raise FileNotFoundError(f"unable to find '{f2}'")
if f1 == f2:
raise ValueError(
"answers and scores are the same file: '{0}'".format(f1))
f"answers and scores are the same file: '{f1}'")

with open(f1, "r") as f:
lines = f.readlines()
Expand All @@ -76,7 +76,7 @@ def private_codalab_wrapper(fct, metric_name, fold1, fold2, f1="answer.txt", f2=
print("First scores:", scores[:10])

metric = fct(answers, scores)
res = "{0}:{1}".format(metric_name, metric)
res = f"{metric_name}:{metric}"
print("Results=", res)
with open(output, "w") as f:
f.write(res)
Expand Down Expand Up @@ -110,5 +110,5 @@ def AUC(answers, scores):

if __name__ == "__main__":
if len(sys.argv) < 3:
raise Exception("bad arguments: {0}".format(sys.argv))
raise Exception(f"bad arguments: {sys.argv}")
main_codalab_wrapper(AUC, "AUC", sys.argv)
4 changes: 2 additions & 2 deletions _doc/examples/automation/copy_lectures.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,13 @@
if "_UT_" in spl:
parent, spl = os.path.split(parent)
if "_UT_" in spl:
raise ValueError("Something is weird with: '{0}'".format(name))
raise ValueError(f"Something is weird with: '{name}'")
index.append((spl, os.path.dirname(name)))
if spl in done:
raise ValueError("Duplicated package '{0}'.\n{1}".format(
spl, "\n".join("{0}={1}".format(k, v) for k, v in sorted(done.items()))))

fLOG("Found {0} directories".format(len(index)))
fLOG(f"Found {len(index)} directories")
for ind in index:
fLOG(" ", ind)

Expand Down
9 changes: 4 additions & 5 deletions _doc/examples/automation/fetch_student_projects_from_gmail.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@
date = "20-Apr-2022"
year = '1A'
exam = 'projet'
pattern = "Python_{0}_{1}".format(year, exam)
pattern = f"Python_{year}_{exam}"
group_def = "groupes.xlsx"
col_subject, col_group, col_mail, col_student = "sujet", "groupe", "mail", "Nom"
final_dest = ["2021-2022", "{}-{}".format(year, exam)]
final_dest = ["2021-2022", f"{year}-{exam}"]


if school == 'ENSAE':
do_mail = True
mailfolder = ["ensae/ENSAE_%s" % year]
mailfolder = [f"ensae/ENSAE_{year}"]
dest_folder = os.path.normpath(os.path.abspath(os.path.join(
*([os.path.dirname(__file__)] + ([".."] * 5) + ["_data", "ecole", school] + final_dest))))
print("dest", dest_folder)
Expand All @@ -74,8 +74,7 @@
df_group = pandas.read_excel(path_df, engine='openpyxl')
for col in [col_subject, col_mail, col_group, col_student]:
if col not in df_group.columns:
raise Exception('{0} not in {1}'.format(
col, list(df_group.columns)))
raise Exception(f'{col} not in {list(df_group.columns)}')
else:
df_group = None

Expand Down
4 changes: 2 additions & 2 deletions _doc/examples/automation/publish_lectures.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,10 @@
if len(modules) == 0:
_ = modules0[0]
one = location % (_, _, suffix[0], "html")
raise ValueError("No module can be updated, for example '{0}'".format(one))
raise ValueError(f"No module can be updated, for example '{one}'")
print("List of modules to publish:")
for i, mod in enumerate(sorted(modules)):
print(" {0}/{1}: {2}".format(i + 1, len(modules), mod))
print(f" {i + 1}/{len(modules)}: {mod}")

##################
# La fonction :func:`publish_teachings_to_web cache` cache beaucoup de chose.
Expand Down
6 changes: 3 additions & 3 deletions _doc/sphinxdoc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,10 @@

texinfo_documents = [
('index',
'%s' % project_var_name,
'%s' % project_var_name_t,
f'{project_var_name}',
f'{project_var_name_t}',
author,
'%s' % project_var_name,
f'{project_var_name}',
'ENSAE, contenu des enseignements',
'teachings'),
]
Expand Down
2 changes: 1 addition & 1 deletion _todo/data/court_chemin/importme.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def import_module(name, moduleName=None, url=None, glo=globals(), loc=locals()):
@param loc locals()
@return modules
"""
file = "%s.py" % name
file = f"{name}.py"
if not os.path.exists(file):
path = "../../../../complements_site_web"
f2 = os.path.join(path, file)
Expand Down
2 changes: 1 addition & 1 deletion _todo/programme/td9_graph_lworld.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
f.write ("var links = [\n")
for l in links :
f.write("{")
f.write( ",".join ( [ "{0}:'{1}'".format (k,v) for k,v in l.items() ] ) )
f.write( ",".join ( [ f"{k}:'{v}'" for k,v in l.items() ] ) )
f.write("},\n")
f.write("\n];\n")

2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
#########

project_var_name = "ensae_teaching_cs"
versionPython = "%s.%s" % (sys.version_info.major, sys.version_info.minor)
versionPython = f"{sys.version_info.major}.{sys.version_info.minor}"
path = "Lib/site-packages/" + project_var_name
readme = 'README.rst'
history = "HISTORY.rst"
Expand Down
2 changes: 1 addition & 1 deletion src/ensae_teaching_cs/automation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from .jenkins_helper import setup_jenkins_server, default_jenkins_jobs
except ImportError as e:
import warnings
warnings.warn("Could not import jenkins_helper '{0}'".format(e))
warnings.warn(f"Could not import jenkins_helper '{e}'")

from .ftp_publish_helper import publish_documentation, publish_teachings_to_web
from .notebook_test_helper import execute_notebooks
Expand Down
38 changes: 18 additions & 20 deletions src/ensae_teaching_cs/automation/ftp_publish_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,8 @@ def trigger_on_specific_strings(content, filename=None, force_allow=None):
(os.environ[env], sub), "somewhere"),
("C:\\%s\\__home_\\%s\\" %
(os.environ[env], sub), "somewhere"),
("C:%s__home_%s" %
(os.environ[env], sub), "somewhere"),
("%s__home_%s" %
(os.environ[env], sub), "somewhere")
(f"C:{os.environ[env]}__home_{sub}", "somewhere"),
(f"{os.environ[env]}__home_{sub}", "somewhere")
])
for s, b in strep:
if s in content:
Expand All @@ -56,7 +54,7 @@ def trigger_on_specific_strings(content, filename=None, force_allow=None):
continue
if s not in force_allow and s in lower_content:
raise Exception(
'string {0}:{1} was found in\n File "{2}", line 1'.format(st, s, filename))
f'string {st}:{s} was found in\n File "{filename}", line 1')
return content


Expand Down Expand Up @@ -145,7 +143,7 @@ def publish_documentation(docs, ftpsite=None, login=None, password=None,
nbnone = len([v for k, v in params.items() if v is None or len(v) == 0])
if nbnone > 0:
raise ValueError(
"One of the following parameters is not specified:\n{0}".format(params))
f"One of the following parameters is not specified:\n{params}")

nbnone = [v for k, v in params.items() if v is None or len(v) == 0]
if len(nbnone) > 0:
Expand Down Expand Up @@ -173,7 +171,7 @@ def combined_transform(ftpp, filename, content):

fLOG("######################################################################")
for k, v in sorted(project.items()):
fLOG("[publish_documentation] loop {}='{}'".format(k, v))
fLOG(f"[publish_documentation] loop {k}='{v}'")

location = project["local"]
root_local = project["root_local"]
Expand All @@ -183,7 +181,7 @@ def combined_transform(ftpp, filename, content):
rootw = project["root_web"]

# documentation + setup
fLOG("[publish_documentation] location='{}'".format(location))
fLOG(f"[publish_documentation] location='{location}'")

ftn = FileTreeNode(root_local)
fftp = FolderTransferFTP(ftn, ftp, sfile, root_web=rootw, fLOG=fLOG, footer_html=footer_html,
Expand Down Expand Up @@ -296,7 +294,7 @@ def publish_teachings_to_web(login, ftpsite="ftp.xavierdupre.fr", # pylint: dis
projects = []
for module in modules:
fLOG(
"[ensae_teaching_cs] PUBLISH '{0}' - layout '{1}'".format(module, layout))
f"[ensae_teaching_cs] PUBLISH '{module}' - layout '{layout}'")
for lay in layout:
for suf in suffix:
root = os.path.abspath(location %
Expand All @@ -308,13 +306,13 @@ def publish_teachings_to_web(login, ftpsite="ftp.xavierdupre.fr", # pylint: dis
p = os.path.abspath(location %
(module, module, suffix[0], lay[0]))
raise FileNotFoundError(
"First tried '{0}'\n last tried '{1}'".format(root, p))
f"First tried '{root}'\n last tried '{p}'")
else:
continue
fLOG(" ", root)
rw = rootw % (module, lay[1])

project = dict(status_file=os.path.join(folder_status, "status_%s.txt" % module),
project = dict(status_file=os.path.join(folder_status, f"status_{module}.txt"),
local=root, root_local=root, root_web=rw)
projects.append(project)

Expand All @@ -335,15 +333,15 @@ def _update_path(pth):
return pth

local = _update_path(root)
fLOG("[ensae_teaching_cs] checking folder '{0}'".format(local))
fLOG("[ensae_teaching_cs] root is '{0}'".format(root))
fLOG(f"[ensae_teaching_cs] checking folder '{local}'")
fLOG(f"[ensae_teaching_cs] root is '{root}'")
if os.path.exists(local):
fLOG("[ensae_teaching_cs] found '{0}'".format(local))
project = dict(status_file=os.path.join(folder_status, "status_3_%s.txt" % module),
fLOG(f"[ensae_teaching_cs] found '{local}'")
project = dict(status_file=os.path.join(folder_status, f"status_3_{module}.txt"),
local=local, root_local=local,
root_web=(rootw % (module, lay[1])).replace("_no_clean", "").replace("/helpsphinx", "/helpsphinx3"))
projects.append(project)
project = dict(status_file=os.path.join(folder_status, "status_2_%s.txt" % module),
project = dict(status_file=os.path.join(folder_status, f"status_2_{module}.txt"),
local=local, root_local=local,
root_web=(rootw % (module, lay[1])).replace("_no_clean", "").replace("/helpsphinx", "/helpsphinx2"))
projects.append(project)
Expand All @@ -357,7 +355,7 @@ def _update_path(pth):
else:
pass
else:
project = dict(status_file=os.path.join(folder_status, "status_doc1_%s.txt" % module),
project = dict(status_file=os.path.join(folder_status, f"status_doc1_{module}.txt"),
local=root1, root_local=root1,
root_web=(rootw % (module, lay[1])).replace("_no_clean", ""))
projects.append(project)
Expand All @@ -368,11 +366,11 @@ def _update_path(pth):
if exc:
raise FileNotFoundError(root3)
else:
project = dict(status_file=os.path.join(folder_status, "status_doc3_%s.txt" % module),
project = dict(status_file=os.path.join(folder_status, f"status_doc3_{module}.txt"),
local=root3, root_local=root3,
root_web=(rootw % (module, lay[1])).replace("_no_clean", "").replace("/helpsphinx", "/helpsphinx3"))
projects.append(project)
project = dict(status_file=os.path.join(folder_status, "status_doc2_%s.txt" % module),
project = dict(status_file=os.path.join(folder_status, f"status_doc2_{module}.txt"),
local=root3, root_local=root3,
root_web=(rootw % (module, lay[1])).replace("_no_clean", "").replace("/helpsphinx", "/helpsphinx2"))
projects.append(project)
Expand All @@ -383,7 +381,7 @@ def _update_path(pth):
if 'root_local' not in proj:
if 'folder' not in proj:
raise KeyError(
"Key 'folder' or 'root_local' must be specified in {}.".format(proj))
f"Key 'folder' or 'root_local' must be specified in {proj}.")
proj = proj.copy()
proj['root_local'] = proj['folder']
if 'folder' not in proj:
Expand Down
4 changes: 2 additions & 2 deletions src/ensae_teaching_cs/automation/jenkins_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,11 @@ def default_jenkins_jobs(filter=None, neg_filter=None, root=None, platform=None)
if reg.search(item[0]) and not neg_reg.search(item[0]):
sub.append(item)
else:
raise TypeError("{0} - {1}".format(item, type(item)))
raise TypeError(f"{item} - {type(item)}")
if len(sub) > 0:
new_res.append(sub)
else:
raise TypeError("{0} - {1}".format(row, type(row)))
raise TypeError(f"{row} - {type(row)}")
return new_res
else:
context = {'Python37': 'python3.7',
Expand Down
5 changes: 2 additions & 3 deletions src/ensae_teaching_cs/automation/notebook_test_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def a_test_notebook_runner(filename, name, folder, valid=None, copy_files=None,
@param fLOG logging function
"""
filename = os.path.abspath(filename)
temp = get_temp_folder(filename, "temp_notebook_123_{0}".format(name))
temp = get_temp_folder(filename, f"temp_notebook_123_{name}")
doc = os.path.normpath(os.path.join(
temp, "..", "..", "..", "_doc", "notebooks", folder))
if not os.path.exists(doc):
Expand All @@ -253,8 +253,7 @@ def a_test_notebook_runner(filename, name, folder, valid=None, copy_files=None,
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
src_file = os.path.join(doc, name_)
fLOG("[a_test_notebook_runner] copy '{0}' to '{1}'.".format(
src_file, dest_dir))
fLOG(f"[a_test_notebook_runner] copy '{src_file}' to '{dest_dir}'.")
shutil.copy(src_file, dest_dir)

import pyquickhelper
Expand Down
Loading

0 comments on commit f00370b

Please sign in to comment.