f-strings everywhere
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent b444e63 · Browse files · 40 files·+188 added−227 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
40 files+188 added−227 removed
- tests:+29 added−27 removed
- other:+159 added−200 removed
Provenance
- Commit
9897d81- Tree
1ae0d18- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
b444e63
40 files changed+188 added−227 removed
modified:docs/advanced.rst+7 added-7 removed
44 unmodified lines45 if not matches:46 return None47 elif len(matches) == 1:48 return click.Group.get_command(self, ctx, matches[0])49- ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))49+ ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")50 51 And it can then be used like this:52 53 .. click:example::37 unmodified lines91 @click.command()92 @click.option('--url', callback=open_url)93 def cli(url, fp=None):94 if fp is not None:95- click.echo('%s: %s' % (url, fp.code))95+ click.echo(f"{url}: {fp.code}")96 97 In this case the callback returns the URL unchanged but also passes a98 second ``fp`` value to the callback. What's more recommended is to pass99 the information in a wrapper however:15 unmodified lines115 @click.command()116 @click.option('--url', callback=open_url)117 def cli(url):118 if url is not None:119- click.echo('%s: %s' % (url.url, url.fp.code))119+ click.echo(f"{url.url}: {url.fp.code}")120 121 122 Token Normalization123 -------------------15 unmodified lines139 140 @click.command(context_settings=CONTEXT_SETTINGS)141 @click.option('--name', default='Pete')142 def cli(name):143- click.echo('Name: %s' % name)143+ click.echo(f"Name: {name}")144 145 And how it works on the command line:146 147 .. click:run::22 unmodified lines170 171 @cli.command()172 @click.option('--count', default=1)173 def test(count):174- click.echo('Count: %d' % count)174+ click.echo(f'Count: {count}')175 176 @cli.command()177 @click.option('--count', default=1)178 @click.pass_context120 unmodified lines299 def cli(verbose, timeit_args):300 """A fake wrapper around Python's timeit."""301 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)302 if verbose:303- click.echo('Invoking: %s' % ' '.join(cmdline))303+ click.echo(f"Invoking: {' '.join(cmdline)}")304 call(cmdline)305 306 And what it looks like:307 87 unmodified lines395 @click.argument('port', nargs=1, default=8080, envvar="PORT")396 @click.pass_context397 def cli(ctx, port):398 source = ctx.get_parameter_source("port")399- click.echo("Port came from {}".format(source))399+ click.echo(f"Port came from {source}")400 401 .. click:run::402 403 invoke(cli, prog_name='cli', args=['8080'])5 unmodified linesmodified:docs/arguments.rst+1 added-1 removed
53 unmodified lines54 @click.argument('dst', nargs=1)55 def copy(src, dst):56 """Move file SRC to DST."""57 for fn in src:58- click.echo('move %s to folder %s' % (fn, dst))58+ click.echo(f"move {fn} to folder {dst}")59 60 And what it looks like:61 62 .. click:run::207 unmodified linesmodified:docs/bashcomplete.rst+3 added-3 removed
48 unmodified lines49 50 @click.command()51 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)52 def cmd1(envvar):53- click.echo('Environment variable: %s' % envvar)54- click.echo('Value: %s' % os.environ[envvar])53+ click.echo(f"Environment variable: {envvar}")54+ click.echo(f"Value: {os.environ[envvar]}")55 56 57 Completion help strings58 -----------------------19 unmodified lines78 79 @click.command()80 @click.argument("color", type=click.STRING, autocompletion=get_colors)81 def cmd1(color):82- click.echo('Chosen color is %s' % color)82+ click.echo(f"Chosen color is {color}")83 84 85 Activation86 ----------77 unmodified linesmodified:docs/commands.rst+5 added-5 removed
23 unmodified lines24 25 @click.group()26 @click.option('--debug/--no-debug', default=False)27 def cli(debug):28- click.echo('Debug mode is %s' % ('on' if debug else 'off'))28+ click.echo(f"Debug mode is {'on' if debug else 'off'}")29 30 @cli.command() # @cli, not @click!31 def sync():32 click.echo('Syncing')62 unmodified lines95 96 @cli.command()97 @click.pass_context98 def sync(ctx):99- click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))99+ click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")100 101 if __name__ == '__main__':102 cli(obj={})103 61 unmodified lines165 def cli(ctx):166 if ctx.invoked_subcommand is None:167 click.echo('I was invoked without subcommand')168 else:169- click.echo('I am about to invoke %s' % ctx.invoked_subcommand)169+ click.echo(f"I am about to invoke {ctx.invoked_subcommand}")170 171 @cli.command()172 def sync():173 click.echo('The subcommand')291 unmodified lines465 466 @cli.command()467 @click.option('--port', default=8000)468 def runserver(port):469- click.echo('Serving on http://127.0.0.1:%d/' % port)469+ click.echo(f"Serving on http://127.0.0.1:{port}/")470 471 if __name__ == '__main__':472 cli(default_map={473 'runserver': {37 unmodified lines511 512 @cli.command()513 @click.option('--port', default=8000)514 def runserver(port):515- click.echo('Serving on http://127.0.0.1:%d/' % port)515+ click.echo(f"Serving on http://127.0.0.1:{port}/")516 517 if __name__ == '__main__':518 cli()519 52 unmodified linesmodified:docs/documentation.rst+2 added-2 removed
22 unmodified lines23 @click.argument('name')24 def hello(count, name):25 """This script prints hello NAME COUNT times."""26 for x in range(count):27- click.echo('Hello %s!' % name)27+ click.echo(f"Hello {name}!")28 29 And what it looks like:30 31 .. click:run::140 unmodified lines172 @click.argument('name', metavar='<name>')173 def hello(count, name):174 """This script prints hello <name> <int> times."""175 for x in range(count):176- click.echo('Hello %s!' % name)176+ click.echo(f"Hello {name}!")177 178 Example:179 180 .. click:run::61 unmodified linesmodified:docs/index.rst+1 added-1 removed
34 unmodified lines35 help='The person to greet.')36 def hello(count, name):37 """Simple program that greets NAME for a total of COUNT times."""38 for x in range(count):39- click.echo('Hello %s!' % name)39+ click.echo(f"Hello {name}!")40 41 if __name__ == '__main__':42 hello()43 64 unmodified linesmodified:docs/options.rst+22 added-18 removed
83 unmodified lines84 @click.command()85 @click.option('--from', '-f', 'from_')86 @click.option('--to', '-t')87 def reserved_param_name(from_, to):88- click.echo('from %s to %s' % (from_, to))88+ click.echo(f"from {from_} to {to}")89 90 And on the command line:91 92 .. click:run::27 unmodified lines120 121 @click.command()122 @click.option('--pos', nargs=2, type=float)123 def findme(pos):124+ a, b = pos124- click.echo('%s / %s' % pos)125+ click.echo(f"{a} / {b}")126 127 And on the command line:128 129 .. click:run::16 unmodified lines146 147 @click.command()148 @click.option('--item', type=(str, int))149 def putitem(item):149- click.echo('name=%s id=%d' % item)150+ name, id = item151+ click.echo(f"name={name} id={id}")152 153 And on the command line:154 155 .. click:run::8 unmodified lines164 165 @click.command()166 @click.option('--item', nargs=2, type=click.Tuple([str, int]))167 def putitem(item):166- click.echo('name=%s id=%d' % item)168+ name, id = item169+ click.echo(f"name={name} id={id}")170 171 .. _multiple-options:172 173 Multiple Options40 unmodified lines214 215 @click.command()216 @click.option('-v', '--verbose', count=True)217 def log(verbose):215- click.echo('Verbosity: %s' % verbose)218+ click.echo(f"Verbosity: {verbose}")219 220 And on the command line:221 222 .. click:run::60 unmodified lines283 284 @click.command()285 @click.option('/debug;/no-debug')286 def log(debug):284- click.echo('debug=%s' % debug)287+ click.echo(f"debug={debug}")288 289 if __name__ == '__main__':290 log()291 112 unmodified lines404 405 @click.command()406 @click.option('--name', prompt=True)407 def hello(name):405- click.echo('Hello %s!' % name)408+ click.echo(f"Hello {name}!")409 410 And what it looks like:411 412 .. click:run::8 unmodified lines421 422 @click.command()423 @click.option('--name', prompt='Your name please')424 def hello(name):422- click.echo('Hello %s!' % name)425+ click.echo(f"Hello {name}!")426 427 What it looks like:428 429 .. click:run::15 unmodified lines445 @click.command()446 @click.option('--password', prompt=True, hide_input=True,447 confirmation_prompt=True)448 def encrypt(password):446- click.echo('Encrypting password to %s' % password.encode('rot13'))449+ click.echo(f"Encrypting password to {password.encode('rot13')}")450 451 What it looks like:452 453 .. click:run::7 unmodified lines461 462 @click.command()463 @click.password_option()464 def encrypt(password):462- click.echo('Encrypting password to %s' % password.encode('rot13'))465+ click.echo(f"Encrypting password to {password.encode('rot13')}")466 467 Dynamic Defaults for Prompts468 ----------------------------469 157 unmodified lines627 628 @click.command()629 @click.option('--username')630 def greet(username):628- click.echo('Hello %s!' % username)631+ click.echo(f'Hello {username}!')632 633 if __name__ == '__main__':634 greet(auto_envvar_prefix='GREETER')635 16 unmodified lines652 653 @click.group()654 @click.option('--debug/--no-debug')655 def cli(debug):653- click.echo('Debug mode is %s' % ('on' if debug else 'off'))656+ click.echo(f"Debug mode is {'on' if debug else 'off'}")657 658 @cli.command()659 @click.option('--username')660 def greet(username):658- click.echo('Hello %s!' % username)661+ click.echo(f"Hello {username}!")662 663 if __name__ == '__main__':664 cli(auto_envvar_prefix='GREETER')665 13 unmodified lines679 680 @click.command()681 @click.option('--username', envvar='USERNAME')682 def greet(username):680- click.echo('Hello %s!' % username)683+ click.echo(f"Hello {username}!")684 685 if __name__ == '__main__':686 greet()687 40 unmodified lines728 729 .. click:run::730 731 import os729- invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep})732+ invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})733 734 Other Prefix Characters735 -----------------------736 7 unmodified lines744 745 @click.command()746 @click.option('+w/-w')747 def chmod(w):745- click.echo('writable=%s' % w)748+ click.echo(f"writable={w}")749 750 if __name__ == '__main__':751 chmod()752 11 unmodified lines764 765 @click.command()766 @click.option('/debug;/no-debug')767 def log(debug):765- click.echo('debug=%s' % debug)768+ click.echo(f"debug={debug}")769 770 if __name__ == '__main__':771 log()772 63 unmodified lines836 837 @click.command()838 @click.option('--rolls', callback=validate_rolls, default='1d6')839 def roll(rolls):837- click.echo('Rolling a %d-sided dice %d time(s)' % rolls)840+ sides, times = rolls841+ click.echo(f"Rolling a {sides}-sided dice {times} time(s)")842 843 if __name__ == '__main__':844 roll()845 7 unmodified linesmodified:docs/quickstart.rst+1 added-1 removed
238 unmodified lines239 @click.option('--count', default=1, help='number of greetings')240 @click.argument('name')241 def hello(count, name):242 for x in range(count):243- click.echo('Hello %s!' % name)243+ click.echo(f"Hello {name}!")244 245 What it looks like:246 247 .. click:run::30 unmodified linesmodified:docs/testing.rst+3 added-3 removed
28 unmodified lines29 30 @click.command()31 @click.argument('name')32 def hello(name):33- click.echo('Hello %s!' % name)33+ click.echo(f'Hello {name}!')34 35 .. code-block:: python36 :caption: test_hello.py37 15 unmodified lines53 54 @click.group()55 @click.option('--debug/--no-debug', default=False)56 def cli(debug):57- click.echo('Debug mode is %s' % ('on' if debug else 'off'))57+ click.echo(f"Debug mode is {'on' if debug else 'off'}")58 59 @cli.command()60 def sync():61 click.echo('Syncing')63 unmodified lines125 126 @click.command()127 @click.option('--foo', prompt=True)128 def prompt(foo):129- click.echo('foo=%s' % foo)129+ click.echo(f"foo={foo}")130 131 .. code-block:: python132 :caption: test_prompt.py133 12 unmodified linesmodified:docs/utils.rst+5 added-6 removed
110 unmodified lines111 .. click:example::112 113 @click.command()114 def less():115- click.echo_via_pager('\n'.join('Line %d' % idx116- for idx in range(200)))115+ click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))116 117 If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string:118 119 .. click:example::120 def _generate_output():121 for idx in range(50000):123- yield "Line %d\n" % idx122+ yield f"Line {idx}\n"123 124 @click.command()125 def less():126 click.echo_via_pager(_generate_output())135 unmodified lines262 context of a full Unicode string.263 264 Example::265 267- click.echo('Path: %s' % click.format_filename(b'foo.txt'))266+ click.echo(f"Path: {click.format_filename(b'foo.txt')}")267 268 269 Standard Streams270 ----------------76 unmodified lines347 parser.read([cfg])348 rv = {}349 for section in parser.sections():350 for key, value in parser.items(section):352- rv['%s.%s' % (section, key)] = value351+ rv[f"{section}.{key}"] = value352 return rv353 354 355 Showing Progress Bars38 unmodified lines394 import time395 396 with click.progressbar([1, 2, 3]) as bar:397 for x in bar:399- print('sleep({})...'.format(x))398+ print(f"sleep({x})...")399 time.sleep(x)400 401 Another useful feature is to associate a label with the progress bar which402 will be shown preceding the progress bar::17 unmodified linesmodified:examples/aliases/aliases.py+1 added-1 removed
63 unmodified lines64 if not matches:65 return None66 elif len(matches) == 1:67 return click.Group.get_command(self, ctx, matches[0])68- ctx.fail("Too many matches: {}".format(", ".join(sorted(matches))))68+ ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")69 70 71 def read_config(ctx, param, value):72 """Callback that is used whenever --config is passed. We use this to66 unmodified linesmodified:examples/bashcompletion/bashcompletion.py+1 added-1 removed
17 unmodified lines18 @cli.command(help="A command to print environment variables")19 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20 def cmd1(envvar):21 click.echo(f"Environment variable: {envvar}")22- click.echo("Value: {}".format(os.environ[envvar]))22+ click.echo(f"Value: {os.environ[envvar]}")23 24 25 @click.group(help="A group that holds a subcommand")26 def group():19 unmodified linesmodified:examples/complex/complex/commands/cmd_init.py+1 added-1 removed
8 unmodified lines9 def cli(ctx, path):10 """Initializes a repository."""11 if path is None:12 path = ctx.home13- ctx.log("Initialized the repository in %s", click.format_filename(path))13+ ctx.log(f"Initialized the repository in {click.format_filename(path)}")modified:examples/imagepipe/imagepipe.py+2 added-3 removed
228 unmodified lines229 def smoothen_cmd(images, iterations):230 """Applies a smoothening filter."""231 for image in images:232 click.echo(233- "Smoothening '{}' {} time{}".format(234- image.filename, iterations, "s" if iterations != 1 else ""235- )233+ f"Smoothening {image.filename!r} {iterations}"234+ f" time{'s' if iterations != 1 else ''}"235 )236 for _ in range(iterations):237 image = copy_filename(image.filter(ImageFilter.BLUR), image)238 yield image50 unmodified linesmodified:examples/repo/repo.py+1 added-1 removed
76 unmodified lines77 of SRC and create that folder.78 """79 if dest is None:80 dest = posixpath.split(src)[-1] or "."81- click.echo("Cloning repo {} to {}".format(src, os.path.abspath(dest)))81+ click.echo(f"Cloning repo {src} to {os.path.basename(dest)}")82 repo.home = dest83 if shallow:84 click.echo("Making shallow checkout")85 click.echo(f"Checking out revision {rev}")81 unmodified linesmodified:examples/termui/termui.py+1 added-1 removed
22 unmodified lines23 def pager():24 """Demonstrates using the pager."""25 lines = []26 for x in range(200):27- lines.append("{}. Hello World!".format(click.style(str(x), fg="green")))27+ lines.append(f"{click.style(str(x), fg='green')}. Hello World!")28 click.echo_via_pager("\n".join(lines))29 30 31 @cli.command()138 unmodified linesmodified:examples/validation/validation.py+1 added-2 removed
15 unmodified lines16 if not isinstance(value, tuple):17 value = urlparse.urlparse(value)18 if value.scheme not in ("http", "https"):19 self.fail(20- "invalid URL scheme ({}). Only HTTP URLs are"21- " allowed".format(value.scheme),20+ f"invalid URL scheme ({value.scheme}). Only HTTP URLs are allowed",21 param,22 ctx,23 )24 return value24 unmodified linesmodified:src/click/_bashcomplete.py+1 added-1 removed
343 unmodified lines344 args = cwords[1:]345 346 for item in get_choices(cli, prog_name, args, incomplete):347 if item[1]:348- echo("{arg}\t{desc}".format(arg=item[0], desc=item[1]))348+ echo(f"{item[0]}\t{item[1]}")349 else:350 echo(item[0])351 352 return True19 unmodified linesmodified:src/click/_compat.py+2 added-2 removed
62 unmodified lines63 encoding,64 errors,65 force_readable=False,66 force_writable=False,67- **extra67+ **extra,68 ):69 self._stream = stream = _FixupStream(stream, force_readable, force_writable)70 super().__init__(stream, encoding, errors, **extra)71 342 unmodified lines414 415 while True:416 tmp_filename = os.path.join(417 os.path.dirname(filename),418- ".__atomic-write{:08x}".format(random.randrange(1 << 32)),418+ f".__atomic-write{random.randrange(1 << 32):08x}",419 )420 try:421 fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)422 break189 unmodified linesmodified:src/click/_termui_impl.py+9 added-12 removed
171 unmodified lines172 pos += f"/{self.length}"173 return pos174 175 def format_pct(self):176- return "{: 4}%".format(int(self.pct * 100))[1:]176+ return f"{int(self.pct * 100): 4}%"[1:]177 178 def format_bar(self):179 if self.length_known:180 bar_length = int(self.pct * self.width)170 unmodified lines351 352 fd, filename = tempfile.mkstemp()353 os.close(fd)354 try:355- if (356- hasattr(os, "system")357- and os.system("more {}".format(shlex.quote(filename))) == 0358- ):355+ if hasattr(os, "system") and os.system(f"more {shlex.quote(filename)}") == 0:356 return _pipepager(generator, "more", color)357 return _nullpager(stdout, generator, color)358 finally:359 os.unlink(filename)10 unmodified lines370 # If we're piping to less we might support colors under the371 # condition that372 cmd_detail = cmd.rsplit("/", 1)[-1].split()373 if color is None and cmd_detail[0] == "less":377- less_flags = "{}{}".format(os.environ.get("LESS", ""), " ".join(cmd_detail[1:]))374+ less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_detail[1:])}"375 if not less_flags:376 env["LESS"] = "-R"377 color = True378 elif "r" in less_flags or "R" in less_flags:41 unmodified lines420 encoding = get_best_encoding(sys.stdout)421 with open_stream(filename, "wb")[0] as f:422 f.write(text.encode(encoding))423 try:427- os.system("{} {}".format(shlex.quote(cmd), shlex.quote(filename)))424+ os.system(f"{shlex.quote(cmd)} {shlex.quote(filename)}")425 finally:426 os.unlink(filename)427 428 36 unmodified lines465 else:466 environ = None467 try:468 c = subprocess.Popen(472- "{} {}".format(shlex.quote(editor), shlex.quote(filename)),469+ f"{shlex.quote(editor)} {shlex.quote(filename)}",470 env=environ,471 shell=True,472 )473 exit_code = c.wait()68 unmodified lines542 null.close()543 elif WIN:544 if locate:545 url = _unquote_file(url)549- args = "explorer /select,{}".format(shlex.quote(url))546+ args = f"explorer /select,{shlex.quote(url)}"547 else:551- args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex.quote(url))548+ args = f"start {'/WAIT' if wait else ''} \"\" {shlex.quote(url)}"549 return os.system(args)550 elif CYGWIN:551 if locate:552 url = _unquote_file(url)556- args = "cygstart {}".format(shlex.quote(os.path.dirname(url)))553+ args = f"cygstart {shlex.quote(os.path.dirname(url))}"554 else:558- args = "cygstart {} {}".format("-w" if wait else "", shlex.quote(url))555+ args = f"cygstart {'-w' if wait else ''} {shlex.quote(url)}"556 return os.system(args)557 558 try:559 if locate:109 unmodified linesmodified:src/click/_textwrap.py+1 added-1 removed
31 unmodified lines32 for idx, line in enumerate(text.splitlines()):33 indent = self.initial_indent34 if idx > 0:35 indent = self.subsequent_indent36- rv.append(indent + line)36+ rv.append(f"{indent}{line}")37 return "\n".join(rv)modified:src/click/_unicodefun.py+5 added-5 removed
53 unmodified lines54 " export LANG=C.UTF-8"55 )56 else:57 extra += (58- "This system lists a couple of UTF-8 supporting locales"59- " that you can pick from. The following suitable"60- " locales were discovered: {}".format(", ".join(sorted(good_locales)))58+ "This system lists some UTF-8 supporting locales that"59+ " you can pick from. The following suitable locales"60+ f" were discovered: {', '.join(sorted(good_locales))}"61 )62 63 bad_locale = None64 for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):5 unmodified lines70 extra += (71 "\n\nClick discovered that you exported a UTF-8 locale"72 " but the locale system could not pick up from it"73 " because it does not exist. The exported locale is"74- " '{}' but it is not supported".format(bad_locale)74+ f" {bad_locale!r} but it is not supported"75 )76 77 raise RuntimeError(78 "Click will abort further execution because Python 3 was"79 " configured to use ASCII as encoding for the environment."80 " Consult https://click.palletsprojects.com/python3/ for"81- " mitigation steps.{}".format(extra)81+ f" mitigation steps.{extra}"82 )modified:src/click/_winconsole.py+1 added-3 removed
211 unmodified lines212 def isatty(self):213 return self.buffer.isatty()214 215 def __repr__(self):216- return "<ConsoleStream name={!r} encoding={!r}>".format(217- self.name, self.encoding218- )216+ return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"217 218 219 class WindowsChunkedWriter:220 """88 unmodified linesmodified:src/click/core.py+28 added-33 removed
34 unmodified lines35 SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."36 SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."37 38 DEPRECATED_HELP_NOTICE = " (DEPRECATED)"39-DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command %(name)s is deprecated."39+DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command {name} is deprecated."40 41 42 def _maybe_show_deprecated_notice(cmd):43 if cmd.deprecated:44- echo(style(DEPRECATED_INVOKE_NOTICE % {"name": cmd.name}, fg="red"), err=True)44+ echo(style(DEPRECATED_INVOKE_NOTICE.format(name=cmd.name), fg="red"), err=True)45 46 47 def fast_exit(code):48 """Exit without garbage collection, this speeds up exit by about 10ms for6 unmodified lines55 56 def _bashcomplete(cmd, prog_name, complete_var=None):57 """Internal handler for the bash completion support."""58 if complete_var is None:59- complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())59+ complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()60 complete_instr = os.environ.get(complete_var)61 if not complete_instr:62 return63 16 unmodified lines80 "Found a multi command as subcommand to a multi command"81 " that is in chain mode. This is not supported."82 )83 raise RuntimeError(84- "{}. Command '{}' is set to chain and '{}' was added as"85- " subcommand but it in itself is a multi command. ('{}' is a {}"86- " within a chained {} named '{}').".format(87- hint,88- base_command.name,89- cmd_name,90- cmd_name,91- cmd.__class__.__name__,92- base_command.__class__.__name__,93- base_command.name,94- )84+ f"{hint}. Command {base_command.name!r} is set to chain and"85+ f" {cmd_name!r} was added as a subcommand but it in itself is a"86+ f" multi command. ({cmd_name!r} is a {type(cmd).__name__}"87+ f" within a chained {type(base_command).__name__} named"88+ f" {base_command.name!r})."89 )90 91 92 def batch(iterable, batch_size):59 unmodified lines152 :param value: the string value to verify153 """154 if value not in cls.VALUES:155 raise ValueError(162- "Invalid ParameterSource value: '{}'. Valid "163- "values are: {}".format(value, ",".join(cls.VALUES))156+ f"Invalid ParameterSource value: {value!r}. Valid"157+ f" values are: {','.join(cls.VALUES)}"158 )159 160 161 class Context:212 unmodified lines374 parent is not None375 and parent.auto_envvar_prefix is not None376 and self.info_name is not None377 ):384- auto_envvar_prefix = "{}_{}".format(385- parent.auto_envvar_prefix, self.info_name.upper()378+ auto_envvar_prefix = (379+ f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"380 )381 else:382 auto_envvar_prefix = auto_envvar_prefix.upper()383 if auto_envvar_prefix is not None:697 unmodified lines1081 value, args = param.handle_parse_result(ctx, opts, args)1082 1083 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1084 ctx.fail(1091- "Got unexpected extra argument{} ({})".format(1092- "s" if len(args) != 1 else "", " ".join(map(make_str, args))1093- )1085+ "Got unexpected extra"1086+ f" argument{'s' if len(args) != 1 else ''}"1087+ f" ({' '.join(map(make_str, args))})"1088 )1089 1090 ctx.args = args1091 return args499 unmodified lines1591 if self.type.is_composite:1592 if self.nargs <= 1:1593 raise TypeError(1594 "Attempted to invoke composite type but nargs has"1601- " been set to {}. This is not supported; nargs"1602- " needs to be set to a fixed value > 1.".format(self.nargs)1595+ f" been set to {self.nargs}. This is not supported;"1596+ " nargs needs to be set to a fixed value > 1."1597 )1598 if self.multiple:1599 return tuple(self.type(x or (), self, ctx) for x in value or ())1600 return self.type(value or (), self, ctx)255 unmodified lines1856 raise TypeError("Could not determine name for option")1857 1858 if not opts and not secondary_opts:1859 raise TypeError(1866- "No options defined but a name was passed ({}). Did you"1867- " mean to declare an argument instead of an option?".format(name)1860+ f"No options defined but a name was passed ({name})."1861+ " Did you mean to declare an argument instead of an"1862+ " option?"1863 )1864 1865 return name, opts, secondary_opts1866 51 unmodified lines1918 if envvar is None:1919 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1920 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"1921 if envvar is not None:1927- extra.append(1928- "env var: {}".format(1929- ", ".join(str(d) for d in envvar)1930- if isinstance(envvar, (list, tuple))1931- else envvar1922+ var_str = (1923+ ", ".join(str(d) for d in envvar)1924+ if isinstance(envvar, (list, tuple))1925+ else envvar1932- )1926 )1927+ extra.append(f"env var: {var_str}")1928 if self.default is not None and (self.show_default or ctx.show_default):1929 if isinstance(self.show_default, str):1930 default_string = f"({self.show_default})"1931 elif isinstance(self.default, (list, tuple)):6 unmodified lines1938 1939 if self.required:1940 extra.append("required")1941 if extra:1948- help = "{}[{}]".format(f"{help} " if help else "", "; ".join(extra))1942+ extra_str = ";".join(extra)1943+ help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"1944 1945 return ("; " if any_prefix_is_slash else " / ").join(rv), help1946 1947 def get_default(self, ctx):107 unmodified lines2055 name = name.replace("-", "_").lower()2056 else:2057 raise TypeError(2058 "Arguments take exactly one parameter declaration, got"2064- " {}".format(len(decls))2059+ f" {len(decls)}."2060 )2061 return name, [arg], []2062 2063 def get_usage_pieces(self, ctx):7 unmodified linesmodified:src/click/decorators.py+3 added-2 removed
64 unmodified lines65 obj = ctx.find_object(object_type)66 if obj is None:67 raise RuntimeError(68 "Managed to invoke callback without a context"69- " object of type '{}' existing".format(object_type.__name__)69+ f" object of type {object_type.__name__!r}"70+ " existing."71 )72 return ctx.invoke(f, obj, *args, **kwargs)73 74 return update_wrapper(new_func, f)21 unmodified lines96 return cls(97 name=name or f.__name__.lower().replace("_", "-"),98 callback=f,99 params=params,99- **attrs100+ **attrs,101 )102 103 104 def command(name=None, cls=None, **attrs):227 unmodified linesmodified:src/click/exceptions.py+7 added-10 removed
51 unmodified lines52 file = get_text_stderr()53 color = None54 hint = ""55 if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:56- hint = "Try '{} {}' for help.\n".format(57- self.ctx.command_path, self.ctx.help_option_names[0]56+ hint = (57+ f"Try '{self.ctx.command_path}"58+ f" {self.ctx.help_option_names[0]}' for help.\n"59 )60 if self.ctx is not None:61 color = self.ctx.color62 echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)74 unmodified lines137 msg += f". {msg_extra}"138 else:139 msg = msg_extra140 140- return "Missing {}{}{}{}".format(141- param_type,142- f" {param_hint}" if param_hint else "",143- ". " if msg else ".",144- msg or "",145- )141+ hint_str = f" {param_hint}" if param_hint else ""142+ return f"Missing {param_type}{hint_str}.{' ' if msg else ''}{msg or ''}"143 144 def __str__(self):145 if self.message is None:146 param_name = self.param.name if self.param else None19 unmodified lines166 def format_message(self):167 bits = [self.message]168 if self.possibilities:169 if len(self.possibilities) == 1:173- bits.append("Did you mean {}?".format(self.possibilities[0]))170+ bits.append(f"Did you mean {self.possibilities[0]}?")171 else:172 possibilities = sorted(self.possibilities)176- bits.append("(Possible options: {})".format(", ".join(possibilities)))173+ bits.append(f"(Possible options: {', '.join(possibilities)})")174 return " ".join(bits)175 176 177 class BadOptionUsage(UsageError):56 unmodified linesmodified:src/click/formatting.py+5 added-9 removed
132 unmodified lines133 :param prog: the program name.134 :param args: whitespace separated list of arguments.135 :param prefix: the prefix for the first line.136 """137- usage_prefix = "{:>{w}}{} ".format(prefix, prog, w=self.current_indent)137+ usage_prefix = f"{prefix:>{self.current_indent}}{prog} "138 text_width = self.width - self.current_indent139 140 if text_width >= (term_len(usage_prefix) + 20):141 # The arguments will fit to the right of the prefix.20 unmodified lines162 self.write("\n")163 164 def write_heading(self, heading):165 """Writes a heading into the buffer."""166- self.write("{:>{w}}{}:\n".format("", heading, w=self.current_indent))166+ self.write(f"{'':>{self.current_indent}}{heading}:\n")167 168 def write_paragraph(self):169 """Writes a paragraph into the buffer."""170 if self.buffer:32 unmodified lines203 204 first_col = min(widths[0], col_max) + col_spacing205 206 for first, second in iter_rows(rows, len(widths)):207- self.write("{:>{w}}{}".format("", first, w=self.current_indent))207+ self.write(f"{'':>{self.current_indent}}{first}")208 if not second:209 self.write("\n")210 continue211 if term_len(first) <= first_col - col_spacing:6 unmodified lines218 wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)219 lines = wrapped_text.splitlines()220 221 if lines:222- self.write("{}\n".format(lines[0]))222+ self.write(f"{lines[0]}\n")223 224 for line in lines[1:]:225- self.write(226- "{:>{w}}{}\n".format(227- "", line, w=first_col + self.current_indent228- )229- )225+ self.write(f"{'':>{first_col + self.current_indent}}{line}\n")226 227 if len(lines) > 1:228 # separate long help from next option229 self.write("\n")50 unmodified linesmodified:src/click/parser.py+3 added-3 removed
98 unmodified lines99 def normalize_opt(opt, ctx):100 if ctx is None or ctx.token_normalize_func is None:101 return opt102 prefix, opt = split_opt(opt)103- return prefix + ctx.token_normalize_func(opt)103+ return f"{prefix}{ctx.token_normalize_func(opt)}"104 105 106 def split_arg_string(string):107 """Given an argument string this attempts to split it into small parts."""252 unmodified lines360 prefix = arg[0]361 unknown_options = []362 363 for ch in arg[1:]:364- opt = normalize_opt(prefix + ch, self.ctx)364+ opt = normalize_opt(f"{prefix}{ch}", self.ctx)365 option = self._short_opt.get(opt)366 i += 1367 368 if not option:29 unmodified lines398 # remaining options and re-attach the prefix, then report that399 # to the state as new larg. This way there is basic combinatorics400 # that can be achieved while still ignoring unknown arguments.401 if self.ignore_unknown_options and unknown_options:402- state.largs.append("{}{}".format(prefix, "".join(unknown_options)))402+ state.largs.append(f"{prefix}{''.join(unknown_options)}")403 404 def _process_opts(self, arg, state):405 explicit_value = None406 # Long option handling happens in two parts. The first part is25 unmodified linesmodified:src/click/termui.py+12 added-12 removed
54 unmodified lines55 text, suffix, show_default=False, default=None, show_choices=True, type=None56 ):57 prompt = text58 if type is not None and show_choices and isinstance(type, Choice):59- prompt += " ({})".format(", ".join(map(str, type.choices)))59+ prompt += f" ({', '.join(map(str, type.choices))})"60 if default is not None and show_default:61- prompt = "{} [{}]".format(prompt, _format_default(default))62- return prompt + suffix61+ prompt = f"{prompt} [{_format_default(default)}]"62+ return f"{prompt}{suffix}"63 64 65 def _format_default(default):66 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):434 unmodified lines501 """502 bits = []503 if fg:504 try:505- bits.append("\033[{}m".format(_ansi_colors[fg]))505+ bits.append(f"\033[{_ansi_colors[fg]}m")506 except KeyError:507- raise TypeError(f"Unknown color '{fg}'")507+ raise TypeError(f"Unknown color {fg!r}")508 if bg:509 try:510- bits.append("\033[{}m".format(_ansi_colors[bg] + 10))510+ bits.append(f"\033[{_ansi_colors[bg] + 10}m")511 except KeyError:512- raise TypeError(f"Unknown color '{bg}'")512+ raise TypeError(f"Unknown color {bg!r}")513 if bold is not None:514- bits.append("\033[{}m".format(1 if bold else 22))514+ bits.append(f"\033[{1 if bold else 22}m")515 if dim is not None:516- bits.append("\033[{}m".format(2 if dim else 22))516+ bits.append(f"\033[{2 if dim else 22}m")517 if underline is not None:518- bits.append("\033[{}m".format(4 if underline else 24))518+ bits.append(f"\033[{4 if underline else 24}m")519 if blink is not None:520- bits.append("\033[{}m".format(5 if blink else 25))520+ bits.append(f"\033[{5 if blink else 25}m")521 if reverse is not None:522- bits.append("\033[{}m".format(7 if reverse else 27))522+ bits.append(f"\033[{7 if reverse else 27}m")523 bits.append(text)524 if reset:525 bits.append(_ansi_reset_all)526 return "".join(bits)162 unmodified linesmodified:src/click/testing.py+3 added-4 removed
97 unmodified lines98 "\r\n", "\n"99 )100 101 def __repr__(self):102- return "<{} {}>".format(103- type(self).__name__, repr(self.exception) if self.exception else "okay"104- )102+ exc_str = repr(self.exception) if self.exception else "okay"103+ return f"<{type(self).__name__} {exc_str}>"104 105 106 class CliRunner:107 """The CLI runner provides functionality to invoke a Click command line86 unmodified lines194 sys.stdout.flush()195 return val196 197 def hidden_input(prompt=None):199- sys.stdout.write("{}\n".format(prompt or ""))198+ sys.stdout.write(f"{prompt or ''}\n")199 sys.stdout.flush()200 return input.readline().rstrip("\r\n")201 202 def _getchar(echo):160 unmodified linesmodified:src/click/types.py+20 added-45 removed
155 unmodified lines156 self.choices = choices157 self.case_sensitive = case_sensitive158 159 def get_metavar(self, param):160- return "[{}]".format("|".join(self.choices))160+ return f"[{'|'.join(self.choices)}]"161 162 def get_missing_message(self, param):163- return "Choose from:\n\t{}.".format(",\n\t".join(self.choices))163+ choice_str = ",\n\t".join(self.choices)164+ return f"Choose from:\n\t{choice_str}"165 166 def convert(self, value, param, ctx):167 # Match through normalization and case sensitivity168 # first do token_normalize_func, then lowercase19 unmodified lines188 if normed_value in normed_choices:189 return normed_choices[normed_value]190 191 self.fail(191- "invalid choice: {}. (choose from {})".format(192- value, ", ".join(self.choices)193- ),192+ f"invalid choice: {value}. (choose from {', '.join(self.choices)})",193 param,194 ctx,195 )196 197 def __repr__(self):199- return "Choice('{}')".format(list(self.choices))198+ return f"Choice({list(self.choices)})"199 200 201 class DateTime(ParamType):202 """The DateTime type converts date strings into `datetime` objects.21 unmodified lines224 def __init__(self, formats=None):225 self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]226 227 def get_metavar(self, param):229- return "[{}]".format("|".join(self.formats))228+ return f"[{'|'.join(self.formats)}]"229 230 def _try_to_convert_date(self, value, format):231 try:232 return datetime.strptime(value, format)7 unmodified lines240 if dtime:241 return dtime242 243 self.fail(245- "invalid datetime format: {}. (choose from {})".format(246- value, ", ".join(self.formats)247- )244+ f"invalid datetime format: {value}. (choose from {', '.join(self.formats)})"245 )246 247 def __repr__(self):248 return "DateTime"42 unmodified lines291 and rv > self.max292 ):293 if self.min is None:294 self.fail(298- "{} is bigger than the maximum valid value {}.".format(299- rv, self.max300- ),295+ f"{rv} is bigger than the maximum valid value {self.max}.",296 param,297 ctx,298 )299 elif self.max is None:300 self.fail(306- "{} is smaller than the minimum valid value {}.".format(307- rv, self.min308- ),301+ f"{rv} is smaller than the minimum valid value {self.min}.",302 param,303 ctx,304 )305 else:306 self.fail(314- "{} is not in the valid range of {} to {}.".format(315- rv, self.min, self.max316- ),307+ f"{rv} is not in the valid range of {self.min} to {self.max}.",308 param,309 ctx,310 )311 return rv45 unmodified lines357 and rv > self.max358 ):359 if self.min is None:360 self.fail(370- "{} is bigger than the maximum valid value {}.".format(371- rv, self.max372- ),361+ f"{rv} is bigger than the maximum valid value {self.max}.",362 param,363 ctx,364 )365 elif self.max is None:366 self.fail(378- "{} is smaller than the minimum valid value {}.".format(379- rv, self.min380- ),367+ f"{rv} is smaller than the minimum valid value {self.min}.",368 param,369 ctx,370 )371 else:372 self.fail(386- "{} is not in the valid range of {} to {}.".format(387- rv, self.min, self.max388- ),373+ f"{rv} is not in the valid range of {self.min} to {self.max}.",374 param,375 ctx,376 )377 return rv112 unmodified lines490 ctx.call_on_close(safecall(f.flush))491 return f492 except OSError as e: # noqa: B014493 self.fail(509- "Could not open file: {}: {}".format(510- filename_to_ui(value), get_strerror(e)511- ),494+ f"Could not open file: {filename_to_ui(value)}: {get_strerror(e)}",495 param,496 ctx,497 )498 83 unmodified lines582 except OSError:583 if not self.exists:584 return self.coerce_path_result(rv)585 self.fail(603- "{} '{}' does not exist.".format(604- self.path_type, filename_to_ui(value)605- ),586+ f"{self.path_type} {filename_to_ui(value)!r} does not exist.",587 param,588 ctx,589 )590 591 if not self.file_okay and stat.S_ISREG(st.st_mode):592 self.fail(612- "{} '{}' is a file.".format(self.path_type, filename_to_ui(value)),593+ f"{self.path_type} {filename_to_ui(value)!r} is a file.",594 param,595 ctx,596 )597 if not self.dir_okay and stat.S_ISDIR(st.st_mode):598 self.fail(618- "{} '{}' is a directory.".format(619- self.path_type, filename_to_ui(value)620- ),599+ f"{self.path_type} {filename_to_ui(value)!r} is a directory.",600 param,601 ctx,602 )603 if self.writable and not os.access(value, os.W_OK):604 self.fail(626- "{} '{}' is not writable.".format(627- self.path_type, filename_to_ui(value)628- ),605+ f"{self.path_type} {filename_to_ui(value)!r} is not writable.",606 param,607 ctx,608 )609 if self.readable and not os.access(value, os.R_OK):610 self.fail(634- "{} '{}' is not readable.".format(635- self.path_type, filename_to_ui(value)636- ),611+ f"{self.path_type} {filename_to_ui(value)!r} is not readable.",612 param,613 ctx,614 )615 18 unmodified lines634 self.types = [convert_type(ty) for ty in types]635 636 @property637 def name(self):663- return "<{}>".format(" ".join(ty.name for ty in self.types))638+ return f"<{' '.join(ty.name for ty in self.types)}>"639 640 @property641 def arity(self):642 return len(self.types)84 unmodified linesmodified:src/click/utils.py+1 added-1 removed
406 unmodified lines407 if folder is None:408 folder = os.path.expanduser("~")409 return os.path.join(folder, app_name)410 if force_posix:411- return os.path.join(os.path.expanduser("~/.{}".format(_posixify(app_name))))411+ return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))412 if sys.platform == "darwin":413 return os.path.join(414 os.path.expanduser("~/Library/Application Support"), app_name415 )29 unmodified linesmodified:tests/test_arguments.py+7 added-5 removed
8 unmodified lines9 @click.command()10 @click.argument("src", nargs=-1)11 @click.argument("dst")12 def copy(src, dst):13- click.echo("src={}".format("|".join(src)))13+ click.echo(f"src={'|'.join(src)}")14 click.echo(f"dst={dst}")15 16 result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])17 assert not result.exception14 unmodified lines32 @click.argument("name", nargs=1)33 @click.argument("point", nargs=2, type=click.INT)34 def copy(name, point):35 click.echo(f"name={name}")36- click.echo("point={0[0]}/{0[1]}".format(point))36+ x, y = point37+ click.echo(f"point={x}/{y}")38 39 result = runner.invoke(copy, ["peter", "1", "2"])40 assert not result.exception41 assert result.output.splitlines() == ["name=peter", "point=1/2"]11 unmodified lines53 54 @click.command()55 @click.argument("item", **opts)56 def copy(item):56- click.echo("name={0[0]} id={0[1]:d}".format(item))57+ name, id = item58+ click.echo(f"name={name} id={id:d}")59 60 result = runner.invoke(copy, ["peter", "1"])61 assert not result.exception62 assert result.output.splitlines() == ["name=peter id=1"]125 unmodified lines188 def test_empty_nargs(runner):189 @click.command()190 @click.argument("arg", nargs=-1)191 def cmd(arg):190- click.echo("arg:{}".format("|".join(arg)))192+ click.echo(f"arg:{'|'.join(arg)}")193 194 result = runner.invoke(cmd, [])195 assert result.exit_code == 0196 assert result.output == "arg:\n"197 198 @click.command()199 @click.argument("arg", nargs=-1, required=True)200 def cmd2(arg):199- click.echo("arg:{}".format("|".join(arg)))201+ click.echo(f"arg:{'|'.join(arg)}")202 203 result = runner.invoke(cmd2, [])204 assert result.exit_code == 2205 assert "Missing argument 'ARG...'" in result.output100 unmodified linesmodified:tests/test_basic.py+5 added-5 removed
106 unmodified lines107 def test_int_option(runner):108 @click.command()109 @click.option("--foo", default=42)110 def cli(foo):111- click.echo("FOO:[{}]".format(foo * 2))111+ click.echo(f"FOO:[{foo * 2}]")112 113 result = runner.invoke(cli, [])114 assert not result.exception115 assert "FOO:[84]" in result.output75 unmodified lines191 click.echo(flag)192 193 result = runner.invoke(cli, ["--flag"])194 assert not result.exception195- assert result.output == "{}\n".format(not default)195+ assert result.output == f"{not default}\n"196 result = runner.invoke(cli, [])197 assert not result.exception198 assert result.output == f"{default}\n"199 106 unmodified lines306 307 @click.command()308 @click.option("-f", type=click.Path(exists=True))309 def showtype(f):310- click.echo("is_file={}".format(os.path.isfile(f)))311- click.echo("is_dir={}".format(os.path.isdir(f)))310+ click.echo(f"is_file={os.path.isfile(f)}")311+ click.echo(f"is_dir={os.path.isdir(f)}")312 313 with runner.isolated_filesystem():314 result = runner.invoke(showtype, ["-f", "xxx"])315 assert "does not exist" in result.output4 unmodified lines320 321 @click.command()322 @click.option("-f", type=click.Path())323 def exists(f):324- click.echo("exists={}".format(os.path.exists(f)))324+ click.echo(f"exists={os.path.exists(f)}")325 326 with runner.isolated_filesystem():327 result = runner.invoke(exists, ["-f", "xxx"])328 assert "exists=False" in result.output231 unmodified linesmodified:tests/test_chain.py+2 added-3 removed
5 unmodified lines6 7 8 def debug():9 click.echo(10- "{}={}".format(11- sys._getframe(1).f_code.co_name, "|".join(click.get_current_context().args)12- )10+ f"{sys._getframe(1).f_code.co_name}"11+ f"={'|'.join(click.get_current_context().args)}"12 )13 14 15 def test_basic_chaining(runner):214 unmodified linesmodified:tests/test_commands.py+2 added-2 removed
208 unmodified lines209 210 @cli.command()211 @click.pass_context212 def sync(ctx):213- click.echo("Debug is {}".format("on" if ctx.obj["DEBUG"] else "off"))213+ click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")214 215 result = runner.invoke(cli, ["sync"])216 assert result.exception is None217 assert result.output == "Debug is off\n"45 unmodified lines263 @click.argument("args", nargs=-1, type=click.UNPROCESSED)264 @click.option("--verbose", "-v", count=True)265 def cli(verbose, args):266 click.echo(f"Verbosity: {verbose}")267- click.echo("Args: {}".format("|".join(args)))267+ click.echo(f"Args: {'|'.join(args)}")268 269 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])270 assert not result.exception271 assert result.output.splitlines() == [29 unmodified linesmodified:tests/test_defaults.py+2 added-2 removed
30 unmodified lines31 @click.option(32 "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT33 )34 def cli(arg):35- for item in arg:36- click.echo("<{0[0]:d}|{0[1]:d}>".format(item))35+ for a, b in arg:36+ click.echo(f"<{a:d}|{b:d}>")37 38 result = runner.invoke(cli, [])39 assert not result.exception40 assert result.output.splitlines() == ["<1|2>", "<3|4>"]modified:tests/test_options.py+7 added-6 removed
42 unmodified lines43 def test_nargs_tup_composite_mult(runner):44 @click.command()45 @click.option("--item", type=(str, int), multiple=True)46 def copy(item):47- for item in item:48- click.echo("name={0[0]} id={0[1]:d}".format(item))47+ for name, id in item:48+ click.echo(f"name={name} id={id:d}")49 50 result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])51 assert not result.exception52 assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]367 unmodified lines420 pass421 422 result = runner.invoke(cmd, ["--help"],)423 assert result.exit_code == 0424+ i = " " * 21425 assert (426 " -C, --config PATH Configuration file to use.\n"426- "{i}\n"427- "{i}If not given, the environment variable CONFIG_FILE is\n"428- "{i}consulted and used if set. If neither are given, a default\n"429- "{i}configuration file is loaded.".format(i=" " * 21)427+ f"{i}\n"428+ f"{i}If not given, the environment variable CONFIG_FILE is\n"429+ f"{i}consulted and used if set. If neither are given, a default\n"430+ f"{i}configuration file is loaded."431 ) in result.output432 433 434 def test_argument_custom_class(runner):123 unmodified linesmodified:tests/test_termui.py+2 added-2 removed
245 unmodified lines246 def cli(f):247 click.echo(f.name)248 249 result = runner.invoke(cli)250- assert result.output == "file [{0}]: \n{0}\n".format(__file__)250+ assert result.output == f"file [{__file__}]: \n{__file__}\n"251 252 253 def test_secho(runner):254 with runner.isolation() as outstreams:98 unmodified lines353 monkeypatch.setattr(354 click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()355 )356 monkeypatch.setattr(click.termui, "_getchar", None)357- assert click.getchar() == special_key_char + key_char357+ assert click.getchar() == f"{special_key_char}{key_char}"358 359 360 @pytest.mark.parametrize(361 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)],8 unmodified linesmodified:tests/test_testing.py+2 added-2 removed
123 unmodified lines124 assert result.output == "hello world\n"125 assert not result.exception126 127 result = runner.invoke(cli, color=True)128- assert result.output == "{}\n".format(click.style("hello world", fg="blue"))128+ assert result.output == f"{click.style('hello world', fg='blue')}\n"129 assert not result.exception130 131 132 def test_with_color_but_pause_not_blocking():79 unmodified lines212 213 def test_env():214 @click.command()215 def cli_env():216- click.echo("ENV={}".format(os.environ["TEST_CLICK_ENV"]))216+ click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")217 218 runner = CliRunner()219 220 env_orig = dict(os.environ)77 unmodified lines