Skip to content

Commit 86afa89

Browse files
authored
Merge pull request #9361 from jdufresne/f-strings
Use f-strings for simple string formatting
2 parents fecfa11 + cdcf74f commit 86afa89

File tree

95 files changed

+257
-260
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

95 files changed

+257
-260
lines changed

docs/pip_sphinxext.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def run(self):
2525
cmd_prefix = cmd_prefix.strip('"')
2626
cmd_prefix = cmd_prefix.strip("'")
2727
usage = dedent(
28-
cmd.usage.replace('%prog', '{} {}'.format(cmd_prefix, cmd.name))
28+
cmd.usage.replace('%prog', f'{cmd_prefix} {cmd.name}')
2929
).strip()
3030
node = nodes.literal_block(usage, usage)
3131
return [node]
@@ -63,7 +63,7 @@ def _format_option(self, option, cmd_name=None):
6363
line += option._long_opts[0]
6464
if option.takes_value():
6565
metavar = option.metavar or option.dest.lower()
66-
line += " <{}>".format(metavar.lower())
66+
line += f" <{metavar.lower()}>"
6767
# fix defaults
6868
opt_help = option.help.replace('%default', str(option.default))
6969
# fix paths with sys.prefix
@@ -123,7 +123,7 @@ def determine_opt_prefix(self, opt_name):
123123
if cmd.cmd_opts.has_option(opt_name):
124124
return command
125125

126-
raise KeyError('Could not identify prefix of opt {}'.format(opt_name))
126+
raise KeyError(f'Could not identify prefix of opt {opt_name}')
127127

128128
def process_options(self):
129129
for option in SUPPORTED_OPTIONS:

news/ea24fc60-675c-4104-9825-39d1ee0a20b7.trivial.rst

Whitespace-only changes.

src/pip/_internal/cli/base_command.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def __init__(self, name, summary, isolated=False):
5555
super().__init__()
5656
parser_kw = {
5757
'usage': self.usage,
58-
'prog': '{} {}'.format(get_prog(), name),
58+
'prog': f'{get_prog()} {name}',
5959
'formatter': UpdatingDefaultsHelpFormatter(),
6060
'add_help_option': False,
6161
'name': name,
@@ -70,7 +70,7 @@ def __init__(self, name, summary, isolated=False):
7070
self.tempdir_registry = None # type: Optional[TempDirRegistry]
7171

7272
# Commands should add options to this option group
73-
optgroup_name = '{} Options'.format(self.name.capitalize())
73+
optgroup_name = f'{self.name.capitalize()} Options'
7474
self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
7575

7676
# Add the general options

src/pip/_internal/cli/cmdoptions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def raise_option_error(parser, option, msg):
4646
option: an Option instance.
4747
msg: the error text.
4848
"""
49-
msg = '{} error: {}'.format(option, msg)
49+
msg = f'{option} error: {msg}'
5050
msg = textwrap.fill(' '.join(msg.split()))
5151
parser.error(msg)
5252

src/pip/_internal/cli/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def main(args=None):
5757
try:
5858
cmd_name, cmd_args = parse_command(args)
5959
except PipError as exc:
60-
sys.stderr.write("ERROR: {}".format(exc))
60+
sys.stderr.write(f"ERROR: {exc}")
6161
sys.stderr.write(os.linesep)
6262
sys.exit(1)
6363

src/pip/_internal/cli/main_parser.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,9 @@ def parse_command(args):
8383
if cmd_name not in commands_dict:
8484
guess = get_similar_commands(cmd_name)
8585

86-
msg = ['unknown command "{}"'.format(cmd_name)]
86+
msg = [f'unknown command "{cmd_name}"']
8787
if guess:
88-
msg.append('maybe you meant "{}"'.format(guess))
88+
msg.append(f'maybe you meant "{guess}"')
8989

9090
raise CommandError(' - '.join(msg))
9191

src/pip/_internal/cli/parser.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def format_description(self, description):
8282
description = description.rstrip()
8383
# dedent, then reindent
8484
description = self.indent_lines(textwrap.dedent(description), " ")
85-
description = '{}:\n{}\n'.format(label, description)
85+
description = f'{label}:\n{description}\n'
8686
return description
8787
else:
8888
return ''
@@ -168,7 +168,7 @@ def check_default(self, option, key, val):
168168
try:
169169
return option.check_value(key, val)
170170
except optparse.OptionValueError as exc:
171-
print("An error occurred during configuration: {}".format(exc))
171+
print(f"An error occurred during configuration: {exc}")
172172
sys.exit(3)
173173

174174
def _get_ordered_configuration_items(self):
@@ -279,4 +279,4 @@ def get_default_values(self):
279279

280280
def error(self, msg):
281281
self.print_usage(sys.stderr)
282-
self.exit(UNKNOWN_ERROR, "{}\n".format(msg))
282+
self.exit(UNKNOWN_ERROR, f"{msg}\n")

src/pip/_internal/cli/progress_bars.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def download_speed(self):
152152
def pretty_eta(self):
153153
# type: () -> str
154154
if self.eta: # type: ignore
155-
return "eta {}".format(self.eta_td) # type: ignore
155+
return f"eta {self.eta_td}" # type: ignore
156156
return ""
157157

158158
def iter(self, it): # type: ignore

src/pip/_internal/commands/cache.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ def format_for_human(self, files):
154154
for filename in files:
155155
wheel = os.path.basename(filename)
156156
size = filesystem.format_file_size(filename)
157-
results.append(' - {} ({})'.format(wheel, size))
157+
results.append(f' - {wheel} ({size})')
158158
logger.info('Cache contents:\n')
159159
logger.info('\n'.join(sorted(results)))
160160

src/pip/_internal/commands/configuration.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ def print_env_var_values(self):
221221
write_output("%s:", 'env_var')
222222
with indent_log():
223223
for key, value in sorted(self.configuration.get_environ_vars()):
224-
env_var = 'PIP_{}'.format(key.upper())
224+
env_var = f'PIP_{key.upper()}'
225225
write_output("%s=%r", env_var, value)
226226

227227
def open_in_editor(self, options, args):

src/pip/_internal/commands/debug.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def get_module_from_module_name(module_name):
6666
module_name = 'pkg_resources'
6767

6868
__import__(
69-
'pip._vendor.{}'.format(module_name),
69+
f'pip._vendor.{module_name}',
7070
globals(),
7171
locals(),
7272
level=0
@@ -126,7 +126,7 @@ def show_tags(options):
126126
formatted_target = target_python.format_given()
127127
suffix = ''
128128
if formatted_target:
129-
suffix = ' (target: {})'.format(formatted_target)
129+
suffix = f' (target: {formatted_target})'
130130

131131
msg = 'Compatible tags: {}{}'.format(len(tags), suffix)
132132
logger.info(msg)

src/pip/_internal/commands/help.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@ def run(self, options, args):
3232
if cmd_name not in commands_dict:
3333
guess = get_similar_commands(cmd_name)
3434

35-
msg = ['unknown command "{}"'.format(cmd_name)]
35+
msg = [f'unknown command "{cmd_name}"']
3636
if guess:
37-
msg.append('maybe you meant "{}"'.format(guess))
37+
msg.append(f'maybe you meant "{guess}"')
3838

3939
raise CommandError(' - '.join(msg))
4040

src/pip/_internal/configuration.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ def get_value(self, key):
164164
try:
165165
return self._dictionary[key]
166166
except KeyError:
167-
raise ConfigurationError("No such key - {}".format(key))
167+
raise ConfigurationError(f"No such key - {key}")
168168

169169
def set_value(self, key, value):
170170
# type: (str, Any) -> None
@@ -193,7 +193,7 @@ def unset_value(self, key):
193193

194194
assert self.load_only
195195
if key not in self._config[self.load_only]:
196-
raise ConfigurationError("No such key - {}".format(key))
196+
raise ConfigurationError(f"No such key - {key}")
197197

198198
fname, parser = self._get_parser_to_modify()
199199

@@ -403,4 +403,4 @@ def _mark_as_modified(self, fname, parser):
403403

404404
def __repr__(self):
405405
# type: () -> str
406-
return "{}({!r})".format(self.__class__.__name__, self._dictionary)
406+
return f"{self.__class__.__name__}({self._dictionary!r})"

src/pip/_internal/distributions/sdist.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def _raise_conflicts(conflicting_with, conflicting_reqs):
5252
requirement=self.req,
5353
conflicting_with=conflicting_with,
5454
description=', '.join(
55-
'{} is incompatible with {}'.format(installed, wanted)
55+
f'{installed} is incompatible with {wanted}'
5656
for installed, wanted in sorted(conflicting)
5757
)
5858
)

src/pip/_internal/exceptions.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -203,11 +203,11 @@ def body(self):
203203
its link already populated by the resolver's _populate_link().
204204
205205
"""
206-
return ' {}'.format(self._requirement_name())
206+
return f' {self._requirement_name()}'
207207

208208
def __str__(self):
209209
# type: () -> str
210-
return '{}\n{}'.format(self.head, self.body())
210+
return f'{self.head}\n{self.body()}'
211211

212212
def _requirement_name(self):
213213
# type: () -> str
@@ -364,8 +364,8 @@ def __init__(self, reason="could not be loaded", fname=None, error=None):
364364
def __str__(self):
365365
# type: () -> str
366366
if self.fname is not None:
367-
message_part = " in {}.".format(self.fname)
367+
message_part = f" in {self.fname}."
368368
else:
369369
assert self.error is not None
370-
message_part = ".\n{}\n".format(self.error)
371-
return "Configuration file {}{}".format(self.reason, message_part)
370+
message_part = f".\n{self.error}\n"
371+
return f"Configuration file {self.reason}{message_part}"

src/pip/_internal/index/collector.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,7 @@ def _get_html_page(link, session=None):
447447
reason += str(exc)
448448
_handle_get_page_fail(link, reason, meth=logger.info)
449449
except requests.ConnectionError as exc:
450-
_handle_get_page_fail(link, "connection error: {}".format(exc))
450+
_handle_get_page_fail(link, f"connection error: {exc}")
451451
except requests.Timeout:
452452
_handle_get_page_fail(link, "timed out")
453453
else:
@@ -656,7 +656,7 @@ def collect_links(self, project_name):
656656
),
657657
]
658658
for link in url_locations:
659-
lines.append('* {}'.format(link))
659+
lines.append(f'* {link}')
660660
logger.debug('\n'.join(lines))
661661

662662
return CollectedLinks(

src/pip/_internal/index/package_finder.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def evaluate_link(self, link):
161161
version = None
162162
if link.is_yanked and not self._allow_yanked:
163163
reason = link.yanked_reason or '<none given>'
164-
return (False, 'yanked for reason: {}'.format(reason))
164+
return (False, f'yanked for reason: {reason}')
165165

166166
if link.egg_fragment:
167167
egg_info = link.egg_fragment
@@ -171,7 +171,7 @@ def evaluate_link(self, link):
171171
if not ext:
172172
return (False, 'not a file')
173173
if ext not in SUPPORTED_EXTENSIONS:
174-
return (False, 'unsupported archive format: {}'.format(ext))
174+
return (False, f'unsupported archive format: {ext}')
175175
if "binary" not in self._formats and ext == WHEEL_EXTENSION:
176176
reason = 'No binaries permitted for {}'.format(
177177
self.project_name)
@@ -204,15 +204,15 @@ def evaluate_link(self, link):
204204

205205
# This should be up by the self.ok_binary check, but see issue 2700.
206206
if "source" not in self._formats and ext != WHEEL_EXTENSION:
207-
reason = 'No sources permitted for {}'.format(self.project_name)
207+
reason = f'No sources permitted for {self.project_name}'
208208
return (False, reason)
209209

210210
if not version:
211211
version = _extract_version_from_fragment(
212212
egg_info, self._canonical_name,
213213
)
214214
if not version:
215-
reason = 'Missing project version for {}'.format(self.project_name)
215+
reason = f'Missing project version for {self.project_name}'
216216
return (False, reason)
217217

218218
match = self._py_version_re.search(version)
@@ -983,7 +983,7 @@ def _find_name_version_sep(fragment, canonical_name):
983983
continue
984984
if canonicalize_name(fragment[:i]) == canonical_name:
985985
return i
986-
raise ValueError("{} does not match {}".format(fragment, canonical_name))
986+
raise ValueError(f"{fragment} does not match {canonical_name}")
987987

988988

989989
def _extract_version_from_fragment(fragment, canonical_name):

src/pip/_internal/locations.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,8 @@ def distutils_scheme(
111111
# NOTE: setting user or home has the side-effect of creating the home dir
112112
# or user base for installations during finalize_options()
113113
# ideally, we'd prefer a scheme class that has no side-effects.
114-
assert not (user and prefix), "user={} prefix={}".format(user, prefix)
115-
assert not (home and prefix), "home={} prefix={}".format(home, prefix)
114+
assert not (user and prefix), f"user={user} prefix={prefix}"
115+
assert not (home and prefix), f"home={home} prefix={prefix}"
116116
i.user = user or i.user
117117
if user or home:
118118
i.prefix = ""
@@ -138,7 +138,7 @@ def distutils_scheme(
138138
i.prefix,
139139
'include',
140140
'site',
141-
'python{}'.format(get_major_minor_version()),
141+
f'python{get_major_minor_version()}',
142142
dist_name,
143143
)
144144

src/pip/_internal/models/direct_url.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def _get_required(d, expected_type, key, default=None):
4646
# type: (Dict[str, Any], Type[T], str, Optional[T]) -> T
4747
value = _get(d, expected_type, key, default)
4848
if value is None:
49-
raise DirectUrlValidationError("{} must have a value".format(key))
49+
raise DirectUrlValidationError(f"{key} must have a value")
5050
return value
5151

5252

src/pip/_internal/models/link.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def __init__(
8383
def __str__(self):
8484
# type: () -> str
8585
if self.requires_python:
86-
rp = ' (requires-python:{})'.format(self.requires_python)
86+
rp = f' (requires-python:{self.requires_python})'
8787
else:
8888
rp = ''
8989
if self.comes_from:
@@ -94,7 +94,7 @@ def __str__(self):
9494

9595
def __repr__(self):
9696
# type: () -> str
97-
return '<Link {}>'.format(self)
97+
return f'<Link {self}>'
9898

9999
@property
100100
def url(self):

src/pip/_internal/models/target_python.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def format_given(self):
8686
('implementation', self.implementation),
8787
]
8888
return ' '.join(
89-
'{}={!r}'.format(key, value) for key, value in key_values
89+
f'{key}={value!r}' for key, value in key_values
9090
if value is not None
9191
)
9292

src/pip/_internal/models/wheel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def __init__(self, filename):
3030
wheel_info = self.wheel_file_re.match(filename)
3131
if not wheel_info:
3232
raise InvalidWheelFilename(
33-
"{} is not a valid wheel filename.".format(filename)
33+
f"{filename} is not a valid wheel filename."
3434
)
3535
self.filename = filename
3636
self.name = wheel_info.group('name').replace('_', '-')

src/pip/_internal/network/auth.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ def _get_url_and_credentials(self, original_url):
199199
(username is not None and password is not None) or
200200
# Credentials were not found
201201
(username is None and password is None)
202-
), "Could not load credentials from url: {}".format(original_url)
202+
), f"Could not load credentials from url: {original_url}"
203203

204204
return url, username, password
205205

@@ -223,7 +223,7 @@ def __call__(self, req):
223223
# Factored out to allow for easy patching in tests
224224
def _prompt_for_password(self, netloc):
225225
# type: (str) -> Tuple[Optional[str], Optional[str], bool]
226-
username = ask_input("User for {}: ".format(netloc))
226+
username = ask_input(f"User for {netloc}: ")
227227
if not username:
228228
return None, None, False
229229
auth = get_keyring_auth(netloc, username)

src/pip/_internal/network/lazy_wheel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ def _stream_response(self, start, end, base_headers=HEADERS):
190190
# type: (int, int, Dict[str, str]) -> Response
191191
"""Return HTTP response to a range request from start to end."""
192192
headers = base_headers.copy()
193-
headers['Range'] = 'bytes={}-{}'.format(start, end)
193+
headers['Range'] = f'bytes={start}-{end}'
194194
# TODO: Get range requests to be correctly cached
195195
headers['Cache-Control'] = 'no-cache'
196196
return self._session.get(self._url, headers=headers, stream=True)

src/pip/_internal/network/session.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,9 +318,9 @@ def add_trusted_host(self, host, source=None, suppress_logging=False):
318318
string came from.
319319
"""
320320
if not suppress_logging:
321-
msg = 'adding trusted host: {!r}'.format(host)
321+
msg = f'adding trusted host: {host!r}'
322322
if source is not None:
323-
msg += ' (from {})'.format(source)
323+
msg += f' (from {source})'
324324
logger.info(msg)
325325

326326
host_port = parse_netloc(host)

src/pip/_internal/operations/build/metadata_legacy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def _find_egg_info(directory):
2626

2727
if not filenames:
2828
raise InstallationError(
29-
"No .egg-info directory found in {}".format(directory)
29+
f"No .egg-info directory found in {directory}"
3030
)
3131

3232
if len(filenames) > 1:

src/pip/_internal/operations/build/wheel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def build_wheel_pep517(
3434
logger.debug('Destination directory: %s', tempd)
3535

3636
runner = runner_with_spinner_message(
37-
'Building wheel for {} (PEP 517)'.format(name)
37+
f'Building wheel for {name} (PEP 517)'
3838
)
3939
with backend.subprocess_runner(runner):
4040
wheel_name = backend.build_wheel(

0 commit comments

Comments
 (0)