Skip to content

Commit 4d1932f

Browse files
authored
Merge pull request #7826 from jaraco/bugfix/6973-format-method
Convert the remaining '%' formatters to '.format'.
2 parents 4653cde + 047e249 commit 4d1932f

Some content is hidden

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

46 files changed

+472
-335
lines changed

docs/pip_sphinxext.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,16 @@ def run(self):
4242
class PipOptions(rst.Directive):
4343

4444
def _format_option(self, option, cmd_name=None):
45-
if cmd_name:
46-
bookmark_line = ".. _`%s_%s`:" % (cmd_name, option._long_opts[0])
47-
else:
48-
bookmark_line = ".. _`%s`:" % option._long_opts[0]
45+
bookmark_line = (
46+
".. _`{cmd_name}_{option._long_opts[0]}`:"
47+
if cmd_name else
48+
".. _`{option._long_opts[0]}`:"
49+
).format(**locals())
4950
line = ".. option:: "
5051
if option._short_opts:
5152
line += option._short_opts[0]
5253
if option._short_opts and option._long_opts:
53-
line += ", %s" % option._long_opts[0]
54+
line += ", " + option._long_opts[0]
5455
elif option._long_opts:
5556
line += option._long_opts[0]
5657
if option.takes_value():
@@ -60,7 +61,7 @@ def _format_option(self, option, cmd_name=None):
6061
opt_help = option.help.replace('%default', str(option.default))
6162
# fix paths with sys.prefix
6263
opt_help = opt_help.replace(sys.prefix, "<sys.prefix>")
63-
return [bookmark_line, "", line, "", " %s" % opt_help, ""]
64+
return [bookmark_line, "", line, "", " " + opt_help, ""]
6465

6566
def _format_options(self, options, cmd_name=None):
6667
for option in options:

news/7826.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Replaced remaining uses of '%' formatting with .format. Fixed two regressions introduced in earlier attempts.

src/pip/_internal/cli/main_parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def create_main_parser():
4848

4949
# create command listing for description
5050
description = [''] + [
51-
'%-27s %s' % (name, command_info.summary)
51+
'{name:27} {command_info.summary}'.format(**locals())
5252
for name, command_info in commands_dict.items()
5353
]
5454
parser.description = '\n'.join(description)

src/pip/_internal/cli/parser.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,14 @@ def __init__(self, *args, **kwargs):
3131
optparse.IndentedHelpFormatter.__init__(self, *args, **kwargs)
3232

3333
def format_option_strings(self, option):
34-
return self._format_option_strings(option, ' <%s>', ', ')
34+
return self._format_option_strings(option)
3535

3636
def _format_option_strings(self, option, mvarfmt=' <{}>', optsep=', '):
3737
"""
3838
Return a comma-separated list of option strings and metavars.
3939
4040
:param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
41-
:param mvarfmt: metavar format string - evaluated as mvarfmt % metavar
41+
:param mvarfmt: metavar format string
4242
:param optsep: separator
4343
"""
4444
opts = []

src/pip/_internal/cli/progress_bars.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
1515

1616
if MYPY_CHECK_RUNNING:
17-
from typing import Any, Dict, List
17+
from typing import Any, Dict, Iterator, List, Tuple
1818

1919
try:
2020
from pip._vendor import colorama
@@ -124,7 +124,7 @@ def update(self):
124124

125125
class BlueEmojiBar(IncrementalBar):
126126

127-
suffix = "%(percent)d%%"
127+
suffix = "{percent:.0f}%"
128128
bar_prefix = " "
129129
bar_suffix = " "
130130
phases = (u"\U0001F539", u"\U0001F537", u"\U0001F535") # type: Any
@@ -203,8 +203,8 @@ class BaseDownloadProgressBar(WindowsMixin, InterruptibleMixin,
203203
DownloadProgressMixin):
204204

205205
file = sys.stdout
206-
message = "%(percent)d%%"
207-
suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s"
206+
message = "{percent:.0f}%"
207+
suffix = "{downloaded} {download_speed} {pretty_eta}"
208208

209209
# NOTE: The "type: ignore" comments on the following classes are there to
210210
# work around https://github.com/python/typing/issues/241
@@ -238,7 +238,7 @@ class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin,
238238
DownloadProgressMixin, Spinner):
239239

240240
file = sys.stdout
241-
suffix = "%(downloaded)s %(download_speed)s"
241+
suffix = "{downloaded} {download_speed}"
242242

243243
def next_phase(self): # type: ignore
244244
if not hasattr(self, "_phaser"):
@@ -247,19 +247,22 @@ def next_phase(self): # type: ignore
247247

248248
def update(self):
249249
# type: () -> None
250-
message = self.message % self
250+
vals = dict(self._load_vals(
251+
'downloaded', 'download_speed', 'pretty_eta', 'percent'))
252+
message = self.message.format(**vals)
251253
phase = self.next_phase()
252-
suffix = self.suffix % self
253-
line = ''.join([
254-
message,
255-
" " if message else "",
256-
phase,
257-
" " if suffix else "",
258-
suffix,
259-
])
260-
254+
suffix = self.suffix.format(**vals)
255+
line = " ".join(filter(None, (message, phase, suffix)))
261256
self.writeln(line)
262257

258+
def _load_vals(self, *names):
259+
# type: (*str) -> Iterator[Tuple[str, Any]]
260+
for name in names:
261+
try:
262+
yield name, getattr(self, name)
263+
except Exception:
264+
pass
265+
263266

264267
BAR_TYPES = {
265268
"off": (DownloadSilentBar, DownloadSilentBar),

src/pip/_internal/cli/req_command.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -342,13 +342,13 @@ def get_requirements(
342342
opts = {'name': self.name}
343343
if options.find_links:
344344
raise CommandError(
345-
'You must give at least one requirement to %(name)s '
346-
'(maybe you meant "pip %(name)s %(links)s"?)' %
347-
dict(opts, links=' '.join(options.find_links)))
345+
'You must give at least one requirement to {name} '
346+
'(maybe you meant "pip {name} {links}"?)'.format(
347+
**dict(opts, links=' '.join(options.find_links))))
348348
else:
349349
raise CommandError(
350-
'You must give at least one requirement to %(name)s '
351-
'(see "pip help %(name)s")' % opts)
350+
'You must give at least one requirement to {name} '
351+
'(see "pip help {name}")'.format(**opts))
352352

353353
return requirements
354354

src/pip/_internal/cli/spinners.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,8 @@ def finish(self, final_status):
106106
# type: (str) -> None
107107
if self._finished:
108108
return
109-
self._update("finished with status '%s'" % (final_status,))
109+
self._update(
110+
"finished with status '{final_status}'".format(**locals()))
110111
self._finished = True
111112

112113

src/pip/_internal/commands/completion.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,29 +10,29 @@
1010
from pip._internal.utils.misc import get_prog
1111

1212
BASE_COMPLETION = """
13-
# pip %(shell)s completion start%(script)s# pip %(shell)s completion end
13+
# pip {shell} completion start{script}# pip {shell} completion end
1414
"""
1515

1616
COMPLETION_SCRIPTS = {
1717
'bash': """
1818
_pip_completion()
19-
{
20-
COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \\
19+
{{
20+
COMPREPLY=( $( COMP_WORDS="${{COMP_WORDS[*]}}" \\
2121
COMP_CWORD=$COMP_CWORD \\
2222
PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) )
23-
}
24-
complete -o default -F _pip_completion %(prog)s
23+
}}
24+
complete -o default -F _pip_completion {prog}
2525
""",
2626
'zsh': """
27-
function _pip_completion {
27+
function _pip_completion {{
2828
local words cword
2929
read -Ac words
3030
read -cn cword
3131
reply=( $( COMP_WORDS="$words[*]" \\
3232
COMP_CWORD=$(( cword-1 )) \\
3333
PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null ))
34-
}
35-
compctl -K _pip_completion %(prog)s
34+
}}
35+
compctl -K _pip_completion {prog}
3636
""",
3737
'fish': """
3838
function __fish_complete_pip
@@ -43,7 +43,7 @@
4343
set -lx PIP_AUTO_COMPLETE 1
4444
string split \\ -- (eval $COMP_WORDS[1])
4545
end
46-
complete -fa "(__fish_complete_pip)" -c %(prog)s
46+
complete -fa "(__fish_complete_pip)" -c {prog}
4747
""",
4848
}
4949

@@ -85,11 +85,10 @@ def run(self, options, args):
8585
shell_options = ['--' + shell for shell in sorted(shells)]
8686
if options.shell in shells:
8787
script = textwrap.dedent(
88-
COMPLETION_SCRIPTS.get(options.shell, '') % {
89-
'prog': get_prog(),
90-
}
88+
COMPLETION_SCRIPTS.get(options.shell, '').format(
89+
prog=get_prog())
9190
)
92-
print(BASE_COMPLETION % {'script': script, 'shell': options.shell})
91+
print(BASE_COMPLETION.format(script=script, shell=options.shell))
9392
else:
9493
sys.stderr.write(
9594
'ERROR: You must pass {}\n' .format(' or '.join(shell_options))

src/pip/_internal/commands/search.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,9 @@ def print_results(hits, name_column_width=None, terminal_width=None):
121121
summary = textwrap.wrap(summary, target_width)
122122
summary = ('\n' + ' ' * (name_column_width + 3)).join(summary)
123123

124-
line = '%-*s - %s' % (name_column_width,
125-
'%s (%s)' % (name, latest), summary)
124+
line = '{name_latest:{name_column_width}} - {summary}'.format(
125+
name_latest='{name} ({latest})'.format(**locals()),
126+
**locals())
126127
try:
127128
write_output(line)
128129
if name in installed_packages:

src/pip/_internal/commands/uninstall.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ def run(self, options, args):
7373
reqs_to_uninstall[canonicalize_name(req.name)] = req
7474
if not reqs_to_uninstall:
7575
raise InstallationError(
76-
'You must give at least one requirement to %(name)s (see '
77-
'"pip help %(name)s")' % dict(name=self.name)
76+
'You must give at least one requirement to {self.name} (see '
77+
'"pip help {self.name}")'.format(**locals())
7878
)
7979

8080
protect_pip_from_modification_on_windows(

0 commit comments

Comments
 (0)