Skip to content

Use f-strings for simple string formatting #9361

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 1 commit into from
Dec 26, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 3 additions & 3 deletions docs/pip_sphinxext.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def run(self):
cmd_prefix = cmd_prefix.strip('"')
cmd_prefix = cmd_prefix.strip("'")
usage = dedent(
cmd.usage.replace('%prog', '{} {}'.format(cmd_prefix, cmd.name))
cmd.usage.replace('%prog', f'{cmd_prefix} {cmd.name}')
).strip()
node = nodes.literal_block(usage, usage)
return [node]
Expand Down Expand Up @@ -63,7 +63,7 @@ def _format_option(self, option, cmd_name=None):
line += option._long_opts[0]
if option.takes_value():
metavar = option.metavar or option.dest.lower()
line += " <{}>".format(metavar.lower())
line += f" <{metavar.lower()}>"
# fix defaults
opt_help = option.help.replace('%default', str(option.default))
# fix paths with sys.prefix
Expand Down Expand Up @@ -123,7 +123,7 @@ def determine_opt_prefix(self, opt_name):
if cmd.cmd_opts.has_option(opt_name):
return command

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

def process_options(self):
for option in SUPPORTED_OPTIONS:
Expand Down
Empty file.
4 changes: 2 additions & 2 deletions src/pip/_internal/cli/base_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __init__(self, name, summary, isolated=False):
super().__init__()
parser_kw = {
'usage': self.usage,
'prog': '{} {}'.format(get_prog(), name),
'prog': f'{get_prog()} {name}',
'formatter': UpdatingDefaultsHelpFormatter(),
'add_help_option': False,
'name': name,
Expand All @@ -70,7 +70,7 @@ def __init__(self, name, summary, isolated=False):
self.tempdir_registry = None # type: Optional[TempDirRegistry]

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

# Add the general options
Expand Down
2 changes: 1 addition & 1 deletion src/pip/_internal/cli/cmdoptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def raise_option_error(parser, option, msg):
option: an Option instance.
msg: the error text.
"""
msg = '{} error: {}'.format(option, msg)
msg = f'{option} error: {msg}'
msg = textwrap.fill(' '.join(msg.split()))
parser.error(msg)

Expand Down
2 changes: 1 addition & 1 deletion src/pip/_internal/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def main(args=None):
try:
cmd_name, cmd_args = parse_command(args)
except PipError as exc:
sys.stderr.write("ERROR: {}".format(exc))
sys.stderr.write(f"ERROR: {exc}")
sys.stderr.write(os.linesep)
sys.exit(1)

Expand Down
4 changes: 2 additions & 2 deletions src/pip/_internal/cli/main_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ def parse_command(args):
if cmd_name not in commands_dict:
guess = get_similar_commands(cmd_name)

msg = ['unknown command "{}"'.format(cmd_name)]
msg = [f'unknown command "{cmd_name}"']
if guess:
msg.append('maybe you meant "{}"'.format(guess))
msg.append(f'maybe you meant "{guess}"')

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

Expand Down
6 changes: 3 additions & 3 deletions src/pip/_internal/cli/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def format_description(self, description):
description = description.rstrip()
# dedent, then reindent
description = self.indent_lines(textwrap.dedent(description), " ")
description = '{}:\n{}\n'.format(label, description)
description = f'{label}:\n{description}\n'
return description
else:
return ''
Expand Down Expand Up @@ -168,7 +168,7 @@ def check_default(self, option, key, val):
try:
return option.check_value(key, val)
except optparse.OptionValueError as exc:
print("An error occurred during configuration: {}".format(exc))
print(f"An error occurred during configuration: {exc}")
sys.exit(3)

def _get_ordered_configuration_items(self):
Expand Down Expand Up @@ -279,4 +279,4 @@ def get_default_values(self):

def error(self, msg):
self.print_usage(sys.stderr)
self.exit(UNKNOWN_ERROR, "{}\n".format(msg))
self.exit(UNKNOWN_ERROR, f"{msg}\n")
2 changes: 1 addition & 1 deletion src/pip/_internal/cli/progress_bars.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def download_speed(self):
def pretty_eta(self):
# type: () -> str
if self.eta: # type: ignore
return "eta {}".format(self.eta_td) # type: ignore
return f"eta {self.eta_td}" # type: ignore
return ""

def iter(self, it): # type: ignore
Expand Down
2 changes: 1 addition & 1 deletion src/pip/_internal/commands/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def format_for_human(self, files):
for filename in files:
wheel = os.path.basename(filename)
size = filesystem.format_file_size(filename)
results.append(' - {} ({})'.format(wheel, size))
results.append(f' - {wheel} ({size})')
logger.info('Cache contents:\n')
logger.info('\n'.join(sorted(results)))

Expand Down
2 changes: 1 addition & 1 deletion src/pip/_internal/commands/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def print_env_var_values(self):
write_output("%s:", 'env_var')
with indent_log():
for key, value in sorted(self.configuration.get_environ_vars()):
env_var = 'PIP_{}'.format(key.upper())
env_var = f'PIP_{key.upper()}'
write_output("%s=%r", env_var, value)

def open_in_editor(self, options, args):
Expand Down
4 changes: 2 additions & 2 deletions src/pip/_internal/commands/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def get_module_from_module_name(module_name):
module_name = 'pkg_resources'

__import__(
'pip._vendor.{}'.format(module_name),
f'pip._vendor.{module_name}',
globals(),
locals(),
level=0
Expand Down Expand Up @@ -126,7 +126,7 @@ def show_tags(options):
formatted_target = target_python.format_given()
suffix = ''
if formatted_target:
suffix = ' (target: {})'.format(formatted_target)
suffix = f' (target: {formatted_target})'

msg = 'Compatible tags: {}{}'.format(len(tags), suffix)
logger.info(msg)
Expand Down
4 changes: 2 additions & 2 deletions src/pip/_internal/commands/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ def run(self, options, args):
if cmd_name not in commands_dict:
guess = get_similar_commands(cmd_name)

msg = ['unknown command "{}"'.format(cmd_name)]
msg = [f'unknown command "{cmd_name}"']
if guess:
msg.append('maybe you meant "{}"'.format(guess))
msg.append(f'maybe you meant "{guess}"')

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

Expand Down
6 changes: 3 additions & 3 deletions src/pip/_internal/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def get_value(self, key):
try:
return self._dictionary[key]
except KeyError:
raise ConfigurationError("No such key - {}".format(key))
raise ConfigurationError(f"No such key - {key}")

def set_value(self, key, value):
# type: (str, Any) -> None
Expand Down Expand Up @@ -193,7 +193,7 @@ def unset_value(self, key):

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

fname, parser = self._get_parser_to_modify()

Expand Down Expand Up @@ -403,4 +403,4 @@ def _mark_as_modified(self, fname, parser):

def __repr__(self):
# type: () -> str
return "{}({!r})".format(self.__class__.__name__, self._dictionary)
return f"{self.__class__.__name__}({self._dictionary!r})"
2 changes: 1 addition & 1 deletion src/pip/_internal/distributions/sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def _raise_conflicts(conflicting_with, conflicting_reqs):
requirement=self.req,
conflicting_with=conflicting_with,
description=', '.join(
'{} is incompatible with {}'.format(installed, wanted)
f'{installed} is incompatible with {wanted}'
for installed, wanted in sorted(conflicting)
)
)
Expand Down
10 changes: 5 additions & 5 deletions src/pip/_internal/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,11 +203,11 @@ def body(self):
its link already populated by the resolver's _populate_link().

"""
return ' {}'.format(self._requirement_name())
return f' {self._requirement_name()}'

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

def _requirement_name(self):
# type: () -> str
Expand Down Expand Up @@ -364,8 +364,8 @@ def __init__(self, reason="could not be loaded", fname=None, error=None):
def __str__(self):
# type: () -> str
if self.fname is not None:
message_part = " in {}.".format(self.fname)
message_part = f" in {self.fname}."
else:
assert self.error is not None
message_part = ".\n{}\n".format(self.error)
return "Configuration file {}{}".format(self.reason, message_part)
message_part = f".\n{self.error}\n"
return f"Configuration file {self.reason}{message_part}"
4 changes: 2 additions & 2 deletions src/pip/_internal/index/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ def _get_html_page(link, session=None):
reason += str(exc)
_handle_get_page_fail(link, reason, meth=logger.info)
except requests.ConnectionError as exc:
_handle_get_page_fail(link, "connection error: {}".format(exc))
_handle_get_page_fail(link, f"connection error: {exc}")
except requests.Timeout:
_handle_get_page_fail(link, "timed out")
else:
Expand Down Expand Up @@ -657,7 +657,7 @@ def collect_links(self, project_name):
),
]
for link in url_locations:
lines.append('* {}'.format(link))
lines.append(f'* {link}')
logger.debug('\n'.join(lines))

return CollectedLinks(
Expand Down
10 changes: 5 additions & 5 deletions src/pip/_internal/index/package_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def evaluate_link(self, link):
version = None
if link.is_yanked and not self._allow_yanked:
reason = link.yanked_reason or '<none given>'
return (False, 'yanked for reason: {}'.format(reason))
return (False, f'yanked for reason: {reason}')

if link.egg_fragment:
egg_info = link.egg_fragment
Expand All @@ -171,7 +171,7 @@ def evaluate_link(self, link):
if not ext:
return (False, 'not a file')
if ext not in SUPPORTED_EXTENSIONS:
return (False, 'unsupported archive format: {}'.format(ext))
return (False, f'unsupported archive format: {ext}')
if "binary" not in self._formats and ext == WHEEL_EXTENSION:
reason = 'No binaries permitted for {}'.format(
self.project_name)
Expand Down Expand Up @@ -204,15 +204,15 @@ def evaluate_link(self, link):

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

if not version:
version = _extract_version_from_fragment(
egg_info, self._canonical_name,
)
if not version:
reason = 'Missing project version for {}'.format(self.project_name)
reason = f'Missing project version for {self.project_name}'
return (False, reason)

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


def _extract_version_from_fragment(fragment, canonical_name):
Expand Down
6 changes: 3 additions & 3 deletions src/pip/_internal/locations.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,8 @@ def distutils_scheme(
# NOTE: setting user or home has the side-effect of creating the home dir
# or user base for installations during finalize_options()
# ideally, we'd prefer a scheme class that has no side-effects.
assert not (user and prefix), "user={} prefix={}".format(user, prefix)
assert not (home and prefix), "home={} prefix={}".format(home, prefix)
assert not (user and prefix), f"user={user} prefix={prefix}"
assert not (home and prefix), f"home={home} prefix={prefix}"
i.user = user or i.user
if user or home:
i.prefix = ""
Expand All @@ -138,7 +138,7 @@ def distutils_scheme(
i.prefix,
'include',
'site',
'python{}'.format(get_major_minor_version()),
f'python{get_major_minor_version()}',
dist_name,
)

Expand Down
2 changes: 1 addition & 1 deletion src/pip/_internal/models/direct_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def _get_required(d, expected_type, key, default=None):
# type: (Dict[str, Any], Type[T], str, Optional[T]) -> T
value = _get(d, expected_type, key, default)
if value is None:
raise DirectUrlValidationError("{} must have a value".format(key))
raise DirectUrlValidationError(f"{key} must have a value")
return value


Expand Down
4 changes: 2 additions & 2 deletions src/pip/_internal/models/link.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def __init__(
def __str__(self):
# type: () -> str
if self.requires_python:
rp = ' (requires-python:{})'.format(self.requires_python)
rp = f' (requires-python:{self.requires_python})'
else:
rp = ''
if self.comes_from:
Expand All @@ -94,7 +94,7 @@ def __str__(self):

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

@property
def url(self):
Expand Down
2 changes: 1 addition & 1 deletion src/pip/_internal/models/target_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def format_given(self):
('implementation', self.implementation),
]
return ' '.join(
'{}={!r}'.format(key, value) for key, value in key_values
f'{key}={value!r}' for key, value in key_values
if value is not None
)

Expand Down
2 changes: 1 addition & 1 deletion src/pip/_internal/models/wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def __init__(self, filename):
wheel_info = self.wheel_file_re.match(filename)
if not wheel_info:
raise InvalidWheelFilename(
"{} is not a valid wheel filename.".format(filename)
f"{filename} is not a valid wheel filename."
)
self.filename = filename
self.name = wheel_info.group('name').replace('_', '-')
Expand Down
4 changes: 2 additions & 2 deletions src/pip/_internal/network/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def _get_url_and_credentials(self, original_url):
(username is not None and password is not None) or
# Credentials were not found
(username is None and password is None)
), "Could not load credentials from url: {}".format(original_url)
), f"Could not load credentials from url: {original_url}"

return url, username, password

Expand All @@ -223,7 +223,7 @@ def __call__(self, req):
# Factored out to allow for easy patching in tests
def _prompt_for_password(self, netloc):
# type: (str) -> Tuple[Optional[str], Optional[str], bool]
username = ask_input("User for {}: ".format(netloc))
username = ask_input(f"User for {netloc}: ")
if not username:
return None, None, False
auth = get_keyring_auth(netloc, username)
Expand Down
2 changes: 1 addition & 1 deletion src/pip/_internal/network/lazy_wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def _stream_response(self, start, end, base_headers=HEADERS):
# type: (int, int, Dict[str, str]) -> Response
"""Return HTTP response to a range request from start to end."""
headers = base_headers.copy()
headers['Range'] = 'bytes={}-{}'.format(start, end)
headers['Range'] = f'bytes={start}-{end}'
# TODO: Get range requests to be correctly cached
headers['Cache-Control'] = 'no-cache'
return self._session.get(self._url, headers=headers, stream=True)
Expand Down
4 changes: 2 additions & 2 deletions src/pip/_internal/network/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,9 +317,9 @@ def add_trusted_host(self, host, source=None, suppress_logging=False):
string came from.
"""
if not suppress_logging:
msg = 'adding trusted host: {!r}'.format(host)
msg = f'adding trusted host: {host!r}'
if source is not None:
msg += ' (from {})'.format(source)
msg += f' (from {source})'
logger.info(msg)

host_port = parse_netloc(host)
Expand Down
2 changes: 1 addition & 1 deletion src/pip/_internal/operations/build/metadata_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def _find_egg_info(directory):

if not filenames:
raise InstallationError(
"No .egg-info directory found in {}".format(directory)
f"No .egg-info directory found in {directory}"
)

if len(filenames) > 1:
Expand Down
2 changes: 1 addition & 1 deletion src/pip/_internal/operations/build/wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def build_wheel_pep517(
logger.debug('Destination directory: %s', tempd)

runner = runner_with_spinner_message(
'Building wheel for {} (PEP 517)'.format(name)
f'Building wheel for {name} (PEP 517)'
)
with backend.subprocess_runner(runner):
wheel_name = backend.build_wheel(
Expand Down
Loading