Skip to content

Commit 13792b5

Browse files
authored
Merge pull request #740 from AA-Turner/f-strings
Use f-strings
2 parents 4de9e84 + af98bbc commit 13792b5

File tree

14 files changed

+120
-136
lines changed

14 files changed

+120
-136
lines changed

flit/__init__.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,16 @@ def find_python_executable(python: Optional[str] = None) -> str:
4242
# see https://github.com/pypa/flit/pull/300 and https://bugs.python.org/issue38905
4343
resolved_python = shutil.which(python)
4444
if resolved_python is None:
45-
raise PythonNotFoundError("Unable to resolve Python executable {!r}".format(python))
45+
raise PythonNotFoundError(f"Unable to resolve Python executable {python!r}")
4646
try:
4747
return subprocess.check_output(
4848
[resolved_python, "-c", "import sys; print(sys.executable)"],
4949
universal_newlines=True,
5050
).strip()
5151
except Exception as e:
5252
raise PythonNotFoundError(
53-
"{} occurred trying to find the absolute filepath of Python executable {!r} ({!r})".format(
54-
e.__class__.__name__, python, resolved_python
55-
)
53+
f"{e.__class__.__name__} occurred trying to find the absolute filepath "
54+
f"of Python executable {python!r} ({resolved_python!r})"
5655
) from e
5756

5857

@@ -175,7 +174,7 @@ def main(argv=None):
175174
"'python3 -m flit.tomlify' to convert it to pyproject.toml")
176175

177176
if args.subcmd not in {'init'} and not args.ini_file.is_file():
178-
sys.exit('Config file {} does not exist'.format(args.ini_file))
177+
sys.exit(f'Config file {args.ini_file} does not exist')
179178

180179
enable_colourful_output(logging.DEBUG if args.debug else logging.INFO)
181180

flit/build.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def main(ini_file: Path, formats=None, gen_setup_py=True, use_vcs=True):
3131
if not formats:
3232
formats = ALL_FORMATS
3333
elif not formats.issubset(ALL_FORMATS):
34-
raise ValueError("Unknown package formats: {}".format(formats - ALL_FORMATS))
34+
raise ValueError(f"Unknown package formats: {formats - ALL_FORMATS}")
3535

3636
sdist_info = wheel_info = None
3737
dist_dir = ini_file.parent / 'dist'
@@ -55,6 +55,6 @@ def main(ini_file: Path, formats=None, gen_setup_py=True, use_vcs=True):
5555
elif 'wheel' in formats:
5656
wheel_info = make_wheel_in(ini_file, dist_dir)
5757
except ConfigError as e:
58-
sys.exit('Config error: {}'.format(e))
58+
sys.exit(f'Config error: {e}')
5959

6060
return SimpleNamespace(wheel=wheel_info, sdist=sdist_info)

flit/init.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def guess_module_name(self):
107107
def update_defaults(self, author, author_email, module, home_page, license):
108108
new_defaults = {'author': author, 'author_email': author_email,
109109
'license': license}
110-
name_chunk_pat = r'\b{}\b'.format(re.escape(module))
110+
name_chunk_pat = rf'\b{re.escape(module)}\b'
111111
if re.search(name_chunk_pat, home_page):
112112
new_defaults['home_page_template'] = \
113113
re.sub(name_chunk_pat, '{modulename}', home_page, flags=re.I)
@@ -136,7 +136,7 @@ def find_readme(self):
136136
class TerminalIniter(IniterBase):
137137
def prompt_text(self, prompt, default, validator, retry_msg="Try again."):
138138
if default is not None:
139-
p = "{} [{}]: ".format(prompt, default)
139+
p = f"{prompt} [{default}]: "
140140
else:
141141
p = prompt + ': '
142142
while True:
@@ -153,14 +153,14 @@ def prompt_options(self, prompt, options, default=None):
153153

154154
print(prompt)
155155
for i, (key, text) in enumerate(options, start=1):
156-
print("{}. {}".format(i, text))
156+
print(f"{i}. {text}")
157157
if key == default:
158158
default_ix = i
159159

160160
while True:
161161
p = "Enter 1-" + str(len(options))
162162
if default_ix is not None:
163-
p += ' [{}]'.format(default_ix)
163+
p += f' [{default_ix}]'
164164
response = input(p+': ')
165165
if (default_ix is not None) and response == '':
166166
return default

flit/install.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -187,8 +187,7 @@ def install_scripts(self, script_defs, scripts_dir):
187187

188188
if sys.platform == 'win32':
189189
cmd_file = script_file.with_suffix('.cmd')
190-
cmd = '@echo off\r\n"{python}" "%~dp0\\{script}" %*\r\n'.format(
191-
python=self.python, script=name)
190+
cmd = f'@echo off\r\n"{self.python}" "%~dp0\\{name}" %*\r\n'
192191
log.debug("Writing script wrapper to %s", cmd_file)
193192
with cmd_file.open('w') as f:
194193
f.write(cmd)

flit/log.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,7 @@ def __init__(self, color=True, datefmt=None):
8888

8989
def formatMessage(self, record):
9090
l = len(record.message)
91-
right_text = '{initial}-{name}'.format(initial=record.levelname[0],
92-
name=record.name)
91+
right_text = f'{record.levelname[0]}-{record.name}'
9392
if l + len(right_text) < self.termwidth:
9493
space = ' ' * (self.termwidth - (l + len(right_text)))
9594
else:

flit/sdist.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -202,37 +202,37 @@ def make_setup_py(self):
202202
before, extra = [], []
203203
if self.module.is_package:
204204
packages, package_data = auto_packages(self.module)
205-
before.append("packages = \\\n%s\n" % pformat(sorted(packages)))
206-
before.append("package_data = \\\n%s\n" % pformat(package_data))
205+
before.append(f"packages = \\\n{pformat(sorted(packages))}\n")
206+
before.append(f"package_data = \\\n{pformat(package_data)}\n")
207207
extra.append("packages=packages,")
208208
extra.append("package_data=package_data,")
209209
else:
210-
extra.append("py_modules={!r},".format([self.module.name]))
210+
extra.append(f"py_modules={[self.module.name]!r},")
211211
if self.module.in_namespace_package:
212212
packages = list(namespace_packages(self.module))
213-
before.append("packages = \\\n%s\n" % pformat(packages))
213+
before.append(f"packages = \\\n{pformat(packages)}\n")
214214
extra.append("packages=packages,")
215215

216216
if self.module.prefix:
217217
package_dir = pformat({'': self.module.prefix})
218-
before.append("package_dir = \\\n%s\n" % package_dir)
218+
before.append(f"package_dir = \\\n{package_dir}\n")
219219
extra.append("package_dir=package_dir,")
220220

221221
install_reqs, extra_reqs = convert_requires(self.reqs_by_extra)
222222
if install_reqs:
223-
before.append("install_requires = \\\n%s\n" % pformat(install_reqs))
223+
before.append(f"install_requires = \\\n{pformat(install_reqs)}\n")
224224
extra.append("install_requires=install_requires,")
225225
if extra_reqs:
226-
before.append("extras_require = \\\n%s\n" % pformat(extra_reqs))
226+
before.append(f"extras_require = \\\n{pformat(extra_reqs)}\n")
227227
extra.append("extras_require=extras_require,")
228228

229229
entrypoints = self.prep_entry_points()
230230
if entrypoints:
231-
before.append("entry_points = \\\n%s\n" % pformat(entrypoints))
231+
before.append(f"entry_points = \\\n{pformat(entrypoints)}\n")
232232
extra.append("entry_points=entry_points,")
233233

234234
if self.metadata.requires_python:
235-
extra.append('python_requires=%r,' % self.metadata.requires_python)
235+
extra.append(f'python_requires={self.metadata.requires_python!r},')
236236

237237
return SETUP.format(
238238
before='\n'.join(before),

flit/tomlify.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ def convert(path):
6060
continue
6161

6262
if '.' in groupname:
63-
groupname = '"{}"'.format(groupname)
64-
f.write('\n[tool.flit.entrypoints.{}]\n'.format(groupname))
63+
groupname = f'"{groupname}"'
64+
f.write(f'\n[tool.flit.entrypoints.{groupname}]\n')
6565
f.write(tomli_w.dumps(OrderedDict(group)))
6666
written_entrypoints = True
6767

flit/upload.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def write_pypirc(repo, file="~/.pypirc"):
158158

159159
with open(file, 'w', encoding='utf-8') as f:
160160
f.write("[pypi]\n"
161-
"username = %s\n" % repo.username)
161+
f"username = {repo.username}\n")
162162

163163
def get_password(repo: RepoDetails):
164164
try:

flit/validate.py

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def _download_and_cache_classifiers():
8484
def _verify_classifiers(classifiers, valid_classifiers):
8585
"""Check classifiers against a set of known classifiers"""
8686
invalid = classifiers - valid_classifiers
87-
return ["Unrecognised classifier: {!r}".format(c)
87+
return [f"Unrecognised classifier: {c!r}"
8888
for c in sorted(invalid)]
8989

9090

@@ -152,8 +152,7 @@ def _is_identifier_attr(s):
152152
valid = _is_identifier_attr(v)
153153

154154
if not valid:
155-
problems.append('Invalid entry point in group {}: '
156-
'{} = {}'.format(groupname, k, v))
155+
problems.append(f'Invalid entry point in group {groupname}: {k} = {v}')
157156
return problems
158157

159158
# Distribution name, not quite the same as a Python identifier
@@ -171,7 +170,7 @@ def validate_name(metadata):
171170
name = metadata.get('name', None)
172171
if name is None or NAME.match(name):
173172
return []
174-
return ['Invalid name: {!r}'.format(name)]
173+
return [f'Invalid name: {name!r}']
175174

176175

177176
def _valid_version_specifier(s):
@@ -184,7 +183,7 @@ def validate_requires_python(metadata):
184183
spec = metadata.get('requires_python', None)
185184
if spec is None or _valid_version_specifier(spec):
186185
return []
187-
return ['Invalid requires-python: {!r}'.format(spec)]
186+
return [f'Invalid requires-python: {spec!r}']
188187

189188
MARKER_VARS = {
190189
'python_version', 'python_full_version', 'os_name', 'sys_platform',
@@ -200,38 +199,37 @@ def validate_environment_marker(em):
200199
# TODO: validate parentheses properly. They're allowed by PEP 508.
201200
parts = MARKER_OP.split(c.strip('()'))
202201
if len(parts) != 3:
203-
problems.append("Invalid expression in environment marker: {!r}".format(c))
202+
problems.append(f"Invalid expression in environment marker: {c!r}")
204203
continue
205204
l, op, r = parts
206205
for var in (l.strip(), r.strip()):
207206
if var[:1] in {'"', "'"}:
208207
if len(var) < 2 or var[-1:] != var[:1]:
209-
problems.append("Invalid string in environment marker: {}".format(var))
208+
problems.append(f"Invalid string in environment marker: {var}")
210209
elif var not in MARKER_VARS:
211-
problems.append("Invalid variable name in environment marker: {!r}".format(var))
210+
problems.append(f"Invalid variable name in environment marker: {var!r}")
212211
return problems
213212

214213
def validate_requires_dist(metadata):
215214
probs = []
216215
for req in metadata.get('requires_dist', []):
217216
m = REQUIREMENT.match(req)
218217
if not m:
219-
probs.append("Could not parse requirement: {!r}".format(req))
218+
probs.append(f"Could not parse requirement: {req!r}")
220219
continue
221220

222221
extras, version, envmark = m.group('extras', 'version', 'envmark')
223222
if not (extras is None or all(NAME.match(e.strip())
224223
for e in extras[1:-1].split(','))):
225-
probs.append("Invalid extras in requirement: {!r}".format(req))
224+
probs.append(f"Invalid extras in requirement: {req!r}")
226225
if version is not None:
227226
if version.startswith('(') and version.endswith(')'):
228227
version = version[1:-1]
229228
if version.startswith('@'):
230229
pass # url specifier TODO: validate URL
231230
elif not _valid_version_specifier(version):
232231
print((extras, version, envmark))
233-
probs.append("Invalid version specifier {!r} in requirement {!r}"
234-
.format(version, req))
232+
probs.append(f"Invalid version specifier {version!r} in requirement {req!r}")
235233
if envmark is not None:
236234
probs.extend(validate_environment_marker(envmark[1:]))
237235
return probs
@@ -241,8 +239,7 @@ def validate_url(url):
241239
return []
242240
probs = []
243241
if not url.startswith(('http://', 'https://')):
244-
probs.append("URL {!r} doesn't start with https:// or http://"
245-
.format(url))
242+
probs.append(f"URL {url!r} doesn't start with https:// or http://")
246243
elif not url.split('//', 1)[1]:
247244
probs.append("URL missing address")
248245
return probs
@@ -253,10 +250,9 @@ def validate_project_urls(metadata):
253250
name, url = prurl.split(',', 1)
254251
url = url.lstrip()
255252
if not name:
256-
probs.append("No name for project URL {!r}".format(url))
253+
probs.append(f"No name for project URL {url!r}")
257254
elif len(name) > 32:
258-
probs.append("Project URL name {!r} longer than 32 characters"
259-
.format(name))
255+
probs.append(f"Project URL name {name!r} longer than 32 characters")
260256
probs.extend(validate_url(url))
261257

262258
return probs

0 commit comments

Comments
 (0)