diff options
| author | David Lord <davidism@gmail.com> | 2020-04-19 22:22:49 -0700 |
|---|---|---|
| committer | David Lord <davidism@gmail.com> | 2020-04-19 23:58:30 -0700 |
| commit | d8bd5b1e6ececb9f8ee7cc05a94216b86ce80aed (patch) | |
| tree | c93a2687fb7fa85449b318e389b899df4918d27b | |
| parent | 56921211a3bdaefcc664994139979d25281167cf (diff) | |
| download | click-d8bd5b1e6ececb9f8ee7cc05a94216b86ce80aed.tar.gz | |
apply pyupgrade --py36-plus
35 files changed, 204 insertions, 233 deletions
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1931abf..3bd3294 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,6 +3,7 @@ repos: rev: v2.2.0 hooks: - id: pyupgrade + args: ["--py36-plus"] - repo: https://github.com/asottile/reorder_python_imports rev: v2.2.0 hooks: diff --git a/examples/aliases/aliases.py b/examples/aliases/aliases.py index bf09500..c01672b 100644 --- a/examples/aliases/aliases.py +++ b/examples/aliases/aliases.py @@ -4,7 +4,7 @@ import os import click -class Config(object): +class Config: """The config in this example only holds aliases.""" def __init__(self): @@ -121,7 +121,7 @@ def commit(): @pass_config def status(config): """Shows the status.""" - click.echo("Status for {}".format(config.path)) + click.echo(f"Status for {config.path}") @cli.command() @@ -135,4 +135,4 @@ def alias(config, alias_, cmd, config_file): """Adds an alias to the specified configuration file.""" config.add_alias(alias_, cmd) config.write_config(config_file) - click.echo("Added '{}' as alias for '{}'".format(alias_, cmd)) + click.echo(f"Added '{alias_}' as alias for '{cmd}'") diff --git a/examples/bashcompletion/bashcompletion.py b/examples/bashcompletion/bashcompletion.py index 0502dbc..592bf19 100644 --- a/examples/bashcompletion/bashcompletion.py +++ b/examples/bashcompletion/bashcompletion.py @@ -18,7 +18,7 @@ def get_env_vars(ctx, args, incomplete): @cli.command(help="A command to print environment variables") @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars) def cmd1(envvar): - click.echo("Environment variable: {}".format(envvar)) + click.echo(f"Environment variable: {envvar}") click.echo("Value: {}".format(os.environ[envvar])) @@ -39,7 +39,7 @@ def list_users(ctx, args, incomplete): @group.command(help="Choose a user") @click.argument("user", type=click.STRING, autocompletion=list_users) def subcmd(user): - click.echo("Chosen user is {}".format(user)) + click.echo(f"Chosen user is {user}") cli.add_command(group) diff --git a/examples/colors/colors.py b/examples/colors/colors.py index 012538d..cb7af31 100644 --- a/examples/colors/colors.py +++ b/examples/colors/colors.py @@ -30,15 +30,11 @@ def cli(): Give it a try! """ for color in all_colors: - click.echo(click.style("I am colored {}".format(color), fg=color)) + click.echo(click.style(f"I am colored {color}", fg=color)) for color in all_colors: - click.echo( - click.style("I am colored {} and bold".format(color), fg=color, bold=True) - ) + click.echo(click.style(f"I am colored {color} and bold", fg=color, bold=True)) for color in all_colors: - click.echo( - click.style("I am reverse colored {}".format(color), fg=color, reverse=True) - ) + click.echo(click.style(f"I am reverse colored {color}", fg=color, reverse=True)) click.echo(click.style("I am blinking", blink=True)) click.echo(click.style("I am underlined", underline=True)) diff --git a/examples/complex/complex/cli.py b/examples/complex/complex/cli.py index bb43613..5d00dba 100644 --- a/examples/complex/complex/cli.py +++ b/examples/complex/complex/cli.py @@ -7,7 +7,7 @@ import click CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX") -class Environment(object): +class Environment: def __init__(self): self.verbose = False self.home = os.getcwd() @@ -39,9 +39,7 @@ class ComplexCLI(click.MultiCommand): def get_command(self, ctx, name): try: - mod = __import__( - "complex.commands.cmd_{}".format(name), None, None, ["cli"] - ) + mod = __import__(f"complex.commands.cmd_{name}", None, None, ["cli"]) except ImportError: return return mod.cli diff --git a/examples/imagepipe/imagepipe.py b/examples/imagepipe/imagepipe.py index d46c33f..95f5c42 100644 --- a/examples/imagepipe/imagepipe.py +++ b/examples/imagepipe/imagepipe.py @@ -60,10 +60,8 @@ def generator(f): @processor def new_func(stream, *args, **kwargs): - for item in stream: - yield item - for item in f(*args, **kwargs): - yield item + yield from stream + yield from f(*args, **kwargs) return update_wrapper(new_func, f) @@ -89,7 +87,7 @@ def open_cmd(images): """ for image in images: try: - click.echo("Opening '{}'".format(image)) + click.echo(f"Opening '{image}'") if image == "-": img = Image.open(click.get_binary_stdin()) img.filename = "-" @@ -97,7 +95,7 @@ def open_cmd(images): img = Image.open(image) yield img except Exception as e: - click.echo("Could not open image '{}': {}".format(image, e), err=True) + click.echo(f"Could not open image '{image}': {e}", err=True) @cli.command("save") @@ -114,12 +112,10 @@ def save_cmd(images, filename): for idx, image in enumerate(images): try: fn = filename.format(idx + 1) - click.echo("Saving '{}' as '{}'".format(image.filename, fn)) + click.echo(f"Saving '{image.filename}' as '{fn}'") yield image.save(fn) except Exception as e: - click.echo( - "Could not save image '{}': {}".format(image.filename, e), err=True - ) + click.echo(f"Could not save image '{image.filename}': {e}", err=True) @cli.command("display") @@ -127,7 +123,7 @@ def save_cmd(images, filename): def display_cmd(images): """Opens all images in an image viewer.""" for image in images: - click.echo("Displaying '{}'".format(image.filename)) + click.echo(f"Displaying '{image.filename}'") image.show() yield image @@ -142,7 +138,7 @@ def resize_cmd(images, width, height): """ for image in images: w, h = (width or image.size[0], height or image.size[1]) - click.echo("Resizing '{}' to {}x{}".format(image.filename, w, h)) + click.echo(f"Resizing '{image.filename}' to {w}x{h}") image.thumbnail((w, h)) yield image @@ -160,7 +156,7 @@ def crop_cmd(images, border): if border is not None: for idx, val in enumerate(box): box[idx] = max(0, val - border) - click.echo("Cropping '{}' by {}px".format(image.filename, border)) + click.echo(f"Cropping '{image.filename}' by {border}px") yield copy_filename(image.crop(box), image) else: yield image @@ -176,7 +172,7 @@ def convert_rotation(ctx, param, value): return (Image.ROTATE_180, 180) if value in ("-90", "270", "l", "left"): return (Image.ROTATE_270, 270) - raise click.BadParameter("invalid rotation '{}'".format(value)) + raise click.BadParameter(f"invalid rotation '{value}'") def convert_flip(ctx, param, value): @@ -187,7 +183,7 @@ def convert_flip(ctx, param, value): return (Image.FLIP_LEFT_RIGHT, "left to right") if value in ("tb", "topbottom", "upsidedown", "ud"): return (Image.FLIP_LEFT_RIGHT, "top to bottom") - raise click.BadParameter("invalid flip '{}'".format(value)) + raise click.BadParameter(f"invalid flip '{value}'") @cli.command("transpose") @@ -201,11 +197,11 @@ def transpose_cmd(images, rotate, flip): for image in images: if rotate is not None: mode, degrees = rotate - click.echo("Rotate '{}' by {}deg".format(image.filename, degrees)) + click.echo(f"Rotate '{image.filename}' by {degrees}deg") image = copy_filename(image.transpose(mode), image) if flip is not None: mode, direction = flip - click.echo("Flip '{}' {}".format(image.filename, direction)) + click.echo(f"Flip '{image.filename}' {direction}") image = copy_filename(image.transpose(mode), image) yield image @@ -217,7 +213,7 @@ def blur_cmd(images, radius): """Applies gaussian blur.""" blur = ImageFilter.GaussianBlur(radius) for image in images: - click.echo("Blurring '{}' by {}px".format(image.filename, radius)) + click.echo(f"Blurring '{image.filename}' by {radius}px") yield copy_filename(image.filter(blur), image) @@ -248,7 +244,7 @@ def smoothen_cmd(images, iterations): def emboss_cmd(images): """Embosses an image.""" for image in images: - click.echo("Embossing '{}'".format(image.filename)) + click.echo(f"Embossing '{image.filename}'") yield copy_filename(image.filter(ImageFilter.EMBOSS), image) @@ -260,7 +256,7 @@ def emboss_cmd(images): def sharpen_cmd(images, factor): """Sharpens an image.""" for image in images: - click.echo("Sharpen '{}' by {}".format(image.filename, factor)) + click.echo(f"Sharpen '{image.filename}' by {factor}") enhancer = ImageEnhance.Sharpness(image) yield copy_filename(enhancer.enhance(max(1.0, factor)), image) @@ -282,13 +278,12 @@ def paste_cmd(images, left, right): yield image return - click.echo("Paste '{}' on '{}'".format(to_paste.filename, image.filename)) + click.echo(f"Paste '{to_paste.filename}' on '{image.filename}'") mask = None if to_paste.mode == "RGBA" or "transparency" in to_paste.info: mask = to_paste image.paste(to_paste, (left, right), mask) - image.filename += "+{}".format(to_paste.filename) + image.filename += f"+{to_paste.filename}" yield image - for image in imageiter: - yield image + yield from imageiter diff --git a/examples/naval/naval.py b/examples/naval/naval.py index b8d31e1..7310e6d 100644 --- a/examples/naval/naval.py +++ b/examples/naval/naval.py @@ -21,7 +21,7 @@ def ship(): @click.argument("name") def ship_new(name): """Creates a new ship.""" - click.echo("Created ship {}".format(name)) + click.echo(f"Created ship {name}") @ship.command("move") @@ -31,7 +31,7 @@ def ship_new(name): @click.option("--speed", metavar="KN", default=10, help="Speed in knots.") def ship_move(ship, x, y, speed): """Moves SHIP to the new location X,Y.""" - click.echo("Moving ship {} to {},{} with speed {}".format(ship, x, y, speed)) + click.echo(f"Moving ship {ship} to {x},{y} with speed {speed}") @ship.command("shoot") @@ -40,7 +40,7 @@ def ship_move(ship, x, y, speed): @click.argument("y", type=float) def ship_shoot(ship, x, y): """Makes SHIP fire to X,Y.""" - click.echo("Ship {} fires to {},{}".format(ship, x, y)) + click.echo(f"Ship {ship} fires to {x},{y}") @cli.group("mine") @@ -61,7 +61,7 @@ def mine(): @click.option("ty", "--drifting", flag_value="drifting", help="Drifting mine.") def mine_set(x, y, ty): """Sets a mine at a specific coordinate.""" - click.echo("Set {} mine at {},{}".format(ty, x, y)) + click.echo(f"Set {ty} mine at {x},{y}") @mine.command("remove") @@ -69,4 +69,4 @@ def mine_set(x, y, ty): @click.argument("y", type=float) def mine_remove(x, y): """Removes a mine at a specific coordinate.""" - click.echo("Removed mine at {},{}".format(x, y)) + click.echo(f"Removed mine at {x},{y}") diff --git a/examples/repo/repo.py b/examples/repo/repo.py index 5fd6ead..ff44d55 100644 --- a/examples/repo/repo.py +++ b/examples/repo/repo.py @@ -5,7 +5,7 @@ import sys import click -class Repo(object): +class Repo: def __init__(self, home): self.home = home self.config = {} @@ -14,10 +14,10 @@ class Repo(object): def set_config(self, key, value): self.config[key] = value if self.verbose: - click.echo(" config[{}] = {}".format(key, value), file=sys.stderr) + click.echo(f" config[{key}] = {value}", file=sys.stderr) def __repr__(self): - return "<Repo {}>".format(self.home) + return f"<Repo {self.home}>" pass_repo = click.make_pass_decorator(Repo) @@ -82,7 +82,7 @@ def clone(repo, src, dest, shallow, rev): repo.home = dest if shallow: click.echo("Making shallow checkout") - click.echo("Checking out revision {}".format(rev)) + click.echo(f"Checking out revision {rev}") @cli.command() @@ -93,7 +93,7 @@ def delete(repo): This will throw away the current repository. """ - click.echo("Destroying repo {}".format(repo.home)) + click.echo(f"Destroying repo {repo.home}") click.echo("Deleted!") @@ -136,7 +136,7 @@ def commit(repo, files, message): marker = "# Files to be committed:" hint = ["", "", marker, "#"] for file in files: - hint.append("# U {}".format(file)) + hint.append(f"# U {file}") message = click.edit("\n".join(hint)) if message is None: click.echo("Aborted!") @@ -147,8 +147,8 @@ def commit(repo, files, message): return else: msg = "\n".join(message) - click.echo("Files to be committed: {}".format(files)) - click.echo("Commit message:\n{}".format(msg)) + click.echo(f"Files to be committed: {files}") + click.echo(f"Commit message:\n{msg}") @cli.command(short_help="Copies files.") @@ -163,4 +163,4 @@ def copy(repo, src, dst, force): files from SRC to DST. """ for fn in src: - click.echo("Copy from {} -> {}".format(fn, dst)) + click.echo(f"Copy from {fn} -> {dst}") diff --git a/examples/termui/termui.py b/examples/termui/termui.py index 7b3da43..b772f13 100644 --- a/examples/termui/termui.py +++ b/examples/termui/termui.py @@ -1,4 +1,3 @@ -# coding: utf-8 import math import random import time @@ -16,8 +15,8 @@ def cli(): def colordemo(): """Demonstrates ANSI color support.""" for color in "red", "green", "blue": - click.echo(click.style("I am colored {}".format(color), fg=color)) - click.echo(click.style("I am background colored {}".format(color), bg=color)) + click.echo(click.style(f"I am colored {color}", fg=color)) + click.echo(click.style(f"I am background colored {color}", bg=color)) @cli.command() @@ -56,7 +55,7 @@ def progress(count): def show_item(item): if item is not None: - return "Item #{}".format(item) + return f"Item #{item}" with click.progressbar( filter(items), @@ -71,7 +70,7 @@ def progress(count): length=count, label="Counting", bar_template="%(label)s %(bar)s | %(info)s", - fill_char=click.style(u"█", fg="cyan"), + fill_char=click.style("█", fg="cyan"), empty_char=" ", ) as bar: for item in bar: @@ -94,7 +93,7 @@ def progress(count): length=count, show_percent=False, label="Slowing progress bar", - fill_char=click.style(u"█", fg="green"), + fill_char=click.style("█", fg="green"), ) as bar: for item in steps: time.sleep(item) @@ -119,13 +118,13 @@ def locate(url): def edit(): """Opens an editor with some text in it.""" MARKER = "# Everything below is ignored\n" - message = click.edit("\n\n{}".format(MARKER)) + message = click.edit(f"\n\n{MARKER}") if message is not None: msg = message.split(MARKER, 1)[0].rstrip("\n") if not msg: click.echo("Empty message!") else: - click.echo("Message:\n{}".format(msg)) + click.echo(f"Message:\n{msg}") else: click.echo("You did not enter anything!") diff --git a/examples/validation/validation.py b/examples/validation/validation.py index 3ca5745..6f87eb0 100644 --- a/examples/validation/validation.py +++ b/examples/validation/validation.py @@ -44,6 +44,6 @@ def cli(count, foo, url): 'If a value is provided it needs to be the value "wat".', param_hint=["--foo"], ) - click.echo("count: {}".format(count)) - click.echo("foo: {}".format(foo)) - click.echo("url: {!r}".format(url)) + click.echo(f"count: {count}") + click.echo(f"foo: {foo}") + click.echo(f"url: {url!r}") diff --git a/src/click/_bashcomplete.py b/src/click/_bashcomplete.py index 9e963f7..1c865f6 100644 --- a/src/click/_bashcomplete.py +++ b/src/click/_bashcomplete.py @@ -94,7 +94,7 @@ def get_completion_script(prog_name, complete_var, shell): return ( script % { - "complete_func": "_{}_completion".format(cf_name), + "complete_func": f"_{cf_name}_completion", "script_names": prog_name, "autocomplete_var": complete_var, } diff --git a/src/click/_compat.py b/src/click/_compat.py index 63bebef..96b0dd8 100644 --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -80,7 +80,7 @@ class _NonClosingTextIOWrapper(io.TextIOWrapper): return self._stream.isatty() -class _FixupStream(object): +class _FixupStream: """The new io interface needs more from streams than streams traditionally implement. As such, this fix-up code is necessary in some circumstances. @@ -359,9 +359,9 @@ def get_strerror(e, default=None): def _wrap_io_open(file, mode, encoding, errors): """Handles not passing ``encoding`` and ``errors`` in binary mode.""" if "b" in mode: - return io.open(file, mode) + return open(file, mode) - return io.open(file, mode, encoding=encoding, errors=errors) + return open(file, mode, encoding=encoding, errors=errors) def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False): @@ -437,7 +437,7 @@ def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True -class _AtomicFile(object): +class _AtomicFile: def __init__(self, f, tmp_filename, real_filename): self._f = f self._tmp_filename = tmp_filename diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py index 2ea695e..84e3fc5 100644 --- a/src/click/_termui_impl.py +++ b/src/click/_termui_impl.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module contains implementations for the termui module. To keep the import time of Click down, some infrequently used functionality is @@ -48,7 +47,7 @@ def _length_hint(obj): return hint -class ProgressBar(object): +class ProgressBar: def __init__( self, iterable, @@ -162,15 +161,15 @@ class ProgressBar(object): hours = t % 24 t //= 24 if t > 0: - return "{}d {:02}:{:02}:{:02}".format(t, hours, minutes, seconds) + return f"{t}d {hours:02}:{minutes:02}:{seconds:02}" else: - return "{:02}:{:02}:{:02}".format(hours, minutes, seconds) + return f"{hours:02}:{minutes:02}:{seconds:02}" return "" def format_pos(self): pos = str(self.pos) if self.length_known: - pos += "/{}".format(self.length) + pos += f"/{self.length}" return pos def format_pct(self): @@ -321,8 +320,7 @@ class ProgressBar(object): raise RuntimeError("You need to use progress bars in a with block.") if self.is_hidden: - for rv in self.iter: - yield rv + yield from self.iter else: for rv in self.iter: self.current_item = rv @@ -391,7 +389,7 @@ def _pipepager(generator, cmd, color): text = strip_ansi(text) c.stdin.write(text.encode(encoding, "replace")) - except (IOError, KeyboardInterrupt): + except (OSError, KeyboardInterrupt): pass else: c.stdin.close() @@ -439,7 +437,7 @@ def _nullpager(stream, generator, color): stream.write(text) -class Editor(object): +class Editor: def __init__(self, editor=None, env=None, require_save=True, extension=".txt"): self.editor = editor self.env = env @@ -456,7 +454,7 @@ class Editor(object): if WIN: return "notepad" for editor in "sensible-editor", "vim", "nano": - if os.system("which {} >/dev/null 2>&1".format(editor)) == 0: + if os.system(f"which {editor} >/dev/null 2>&1") == 0: return editor return "vi" @@ -477,9 +475,9 @@ class Editor(object): ) exit_code = c.wait() if exit_code != 0: - raise ClickException("{}: Editing failed!".format(editor)) + raise ClickException(f"{editor}: Editing failed!") except OSError as e: - raise ClickException("{}: Editing failed: {}".format(editor, e)) + raise ClickException(f"{editor}: Editing failed: {e}") def edit(self, text): import tempfile @@ -579,11 +577,11 @@ def open_url(url, wait=False, locate=False): def _translate_ch_to_exc(ch): - if ch == u"\x03": + if ch == "\x03": raise KeyboardInterrupt() - if ch == u"\x04" and not WIN: # Unix-like, Ctrl+D + if ch == "\x04" and not WIN: # Unix-like, Ctrl+D raise EOFError() - if ch == u"\x1a" and WIN: # Windows, Ctrl+Z + if ch == "\x1a" and WIN: # Windows, Ctrl+Z raise EOFError() @@ -630,7 +628,7 @@ if WIN: func = msvcrt.getwch rv = func() - if rv in (u"\x00", u"\xe0"): + if rv in ("\x00", "\xe0"): # \x00 and \xe0 are control characters that indicate special key, # see above. rv += func() diff --git a/src/click/_winconsole.py b/src/click/_winconsole.py index 5a3cdaa..c46081f 100644 --- a/src/click/_winconsole.py +++ b/src/click/_winconsole.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # This module is based on the excellent work by Adam Bartoš who # provided a lot of what went into the implementation here in # the discussion to issue1602 in the Python bug tracker. @@ -146,7 +145,7 @@ class _WindowsConsoleReader(_WindowsConsoleRawIOBase): # wait for KeyboardInterrupt time.sleep(0.1) if not rv: - raise OSError("Windows error: {}".format(GetLastError())) + raise OSError(f"Windows error: {GetLastError()}") if buffer[0] == EOF: return 0 @@ -163,7 +162,7 @@ class _WindowsConsoleWriter(_WindowsConsoleRawIOBase): return "ERROR_SUCCESS" elif errno == ERROR_NOT_ENOUGH_MEMORY: return "ERROR_NOT_ENOUGH_MEMORY" - return "Windows error {}".format(errno) + return f"Windows error {errno}" def write(self, b): bytes_to_be_written = len(b) @@ -185,7 +184,7 @@ class _WindowsConsoleWriter(_WindowsConsoleRawIOBase): return bytes_written -class ConsoleStream(object): +class ConsoleStream: def __init__(self, text_stream, byte_stream): self._text_stream = text_stream self.buffer = byte_stream @@ -219,7 +218,7 @@ class ConsoleStream(object): ) -class WindowsChunkedWriter(object): +class WindowsChunkedWriter: """ Wraps a stream (such as stdout), acting as a transparent proxy for all attribute access apart from method 'write()' which we wrap to write in diff --git a/src/click/core.py b/src/click/core.py index 1f88902..78b9ce4 100644 --- a/src/click/core.py +++ b/src/click/core.py @@ -132,7 +132,7 @@ def iter_params_for_processing(invocation_order, declaration_order): return sorted(declaration_order, key=sort_key) -class ParameterSource(object): +class ParameterSource: """This is an enum that indicates the source of a command line parameter. The enum has one of the following values: COMMANDLINE, @@ -164,7 +164,7 @@ class ParameterSource(object): ) -class Context(object): +class Context: """The context is a special internal object that holds state relevant for the script execution at every single level. It's normally invisible to commands unless they opt-in to getting access to it. @@ -513,7 +513,7 @@ class Context(object): if self.info_name is not None: rv = self.info_name if self.parent is not None: - rv = "{} {}".format(self.parent.command_path, rv) + rv = f"{self.parent.command_path} {rv}" return rv.lstrip() def find_root(self): @@ -666,7 +666,7 @@ class Context(object): return self._source_by_paramname[name] -class BaseCommand(object): +class BaseCommand: """The base command implements the minimal API contract of commands. Most code will never use this as it does not implement a lot of useful functionality but it can act as the direct subclass of alternative @@ -707,7 +707,7 @@ class BaseCommand(object): self.context_settings = context_settings def __repr__(self): - return "<{} {}>".format(self.__class__.__name__, self.name) + return f"<{self.__class__.__name__} {self.name}>" def get_usage(self, ctx): raise NotImplementedError("Base commands cannot get usage") @@ -757,7 +757,7 @@ class BaseCommand(object): prog_name=None, complete_var=None, standalone_mode=True, - **extra + **extra, ): """This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate @@ -832,7 +832,7 @@ class BaseCommand(object): raise e.show() sys.exit(e.exit_code) - except IOError as e: + except OSError as e: if e.errno == errno.EPIPE: sys.stdout = PacifyFlushWrapper(sys.stdout) sys.stderr = PacifyFlushWrapper(sys.stderr) @@ -935,7 +935,7 @@ class Command(BaseCommand): self.deprecated = deprecated def __repr__(self): - return "<{} {}>".format(self.__class__.__name__, self.name) + return f"<{self.__class__.__name__} {self.name}>" def get_usage(self, ctx): """Formats the usage line into a string and returns it. @@ -1140,7 +1140,7 @@ class MultiCommand(Command): subcommand_metavar=None, chain=False, result_callback=None, - **attrs + **attrs, ): Command.__init__(self, name, **attrs) if no_args_is_help is None: @@ -1350,7 +1350,7 @@ class MultiCommand(Command): if cmd is None and not ctx.resilient_parsing: if split_opt(cmd_name)[0]: self.parse_args(ctx, ctx.args) - ctx.fail("No such command '{}'.".format(original_cmd_name)) + ctx.fail(f"No such command '{original_cmd_name}'.") return cmd_name, cmd, args[1:] @@ -1457,7 +1457,7 @@ class CommandCollection(MultiCommand): return sorted(rv) -class Parameter(object): +class Parameter: r"""A parameter to a command comes in two versions: they are either :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently not supported by design as some of the internals for parsing are @@ -1545,7 +1545,7 @@ class Parameter(object): self.autocompletion = autocompletion def __repr__(self): - return "<{} {}>".format(self.__class__.__name__, self.name) + return f"<{self.__class__.__name__} {self.name}>" @property def human_readable_name(self): @@ -1755,7 +1755,7 @@ class Option(Parameter): hidden=False, show_choices=True, show_envvar=False, - **attrs + **attrs, ): default_is_missing = attrs.get("default", _missing) is _missing Parameter.__init__(self, param_decls, type=type, **attrs) @@ -1885,7 +1885,7 @@ class Option(Parameter): if self.is_flag: kwargs.pop("nargs", None) - action_const = "{}_const".format(action) + action_const = f"{action}_const" if self.is_bool_flag and self.secondary_opts: parser.add_option(self.opts, action=action_const, const=True, **kwargs) parser.add_option( @@ -1909,7 +1909,7 @@ class Option(Parameter): if any_slashes: any_prefix_is_slash[:] = [True] if not self.is_flag and not self.count: - rv += " {}".format(self.make_metavar()) + rv += f" {self.make_metavar()}" return rv rv = [_write_opts(self.opts)] @@ -1922,7 +1922,7 @@ class Option(Parameter): envvar = self.envvar if envvar is None: if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None: - envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper()) + envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" if envvar is not None: extra.append( "env var: {}".format( @@ -1933,21 +1933,19 @@ class Option(Parameter): ) if self.default is not None and (self.show_default or ctx.show_default): if isinstance(self.show_default, str): - default_string = "({})".format(self.show_default) + default_string = f"({self.show_default})" elif isinstance(self.default, (list, tuple)): default_string = ", ".join(str(d) for d in self.default) elif inspect.isfunction(self.default): default_string = "(dynamic)" else: default_string = self.default - extra.append("default: {}".format(default_string)) + extra.append(f"default: {default_string}") if self.required: extra.append("required") if extra: - help = "{}[{}]".format( - "{} ".format(help) if help else "", "; ".join(extra) - ) + help = "{}[{}]".format(f"{help} " if help else "", "; ".join(extra)) return ("; " if any_prefix_is_slash else " / ").join(rv), help @@ -1992,7 +1990,7 @@ class Option(Parameter): if rv is not None: return rv if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None: - envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper()) + envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" return os.environ.get(envvar) def value_from_envvar(self, ctx): @@ -2047,7 +2045,7 @@ class Argument(Parameter): if not var: var = self.name.upper() if not self.required: - var = "[{}]".format(var) + var = f"[{var}]" if self.nargs != 1: var += "..." return var diff --git a/src/click/exceptions.py b/src/click/exceptions.py index f75f4db..2776a02 100644 --- a/src/click/exceptions.py +++ b/src/click/exceptions.py @@ -28,7 +28,7 @@ class ClickException(Exception): def show(self, file=None): if file is None: file = get_text_stderr() - echo("Error: {}".format(self.format_message()), file=file) + echo(f"Error: {self.format_message()}", file=file) class UsageError(ClickException): @@ -58,8 +58,8 @@ class UsageError(ClickException): ) if self.ctx is not None: color = self.ctx.color - echo("{}\n{}".format(self.ctx.get_usage(), hint), file=file, color=color) - echo("Error: {}".format(self.format_message()), file=file, color=color) + echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) + echo(f"Error: {self.format_message()}", file=file, color=color) class BadParameter(UsageError): @@ -91,10 +91,10 @@ class BadParameter(UsageError): elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) else: - return "Invalid value: {}".format(self.message) + return f"Invalid value: {self.message}" param_hint = _join_param_hints(param_hint) - return "Invalid value for {}: {}".format(param_hint, self.message) + return f"Invalid value for {param_hint}: {self.message}" class MissingParameter(BadParameter): @@ -133,13 +133,13 @@ class MissingParameter(BadParameter): msg_extra = self.param.type.get_missing_message(self.param) if msg_extra: if msg: - msg += ". {}".format(msg_extra) + msg += f". {msg_extra}" else: msg = msg_extra return "Missing {}{}{}{}".format( param_type, - " {}".format(param_hint) if param_hint else "", + f" {param_hint}" if param_hint else "", ". " if msg else ".", msg or "", ) @@ -147,7 +147,7 @@ class MissingParameter(BadParameter): def __str__(self): if self.message is None: param_name = self.param.name if self.param else None - return "missing parameter: {}".format(param_name) + return f"missing parameter: {param_name}" else: return self.message @@ -161,7 +161,7 @@ class NoSuchOption(UsageError): def __init__(self, option_name, message=None, possibilities=None, ctx=None): if message is None: - message = "no such option: {}".format(option_name) + message = f"no such option: {option_name}" UsageError.__init__(self, message, ctx) self.option_name = option_name self.possibilities = possibilities @@ -216,7 +216,7 @@ class FileError(ClickException): self.filename = filename def format_message(self): - return "Could not open file {}: {}".format(self.ui_filename, self.message) + return f"Could not open file {self.ui_filename}: {self.message}" class Abort(RuntimeError): diff --git a/src/click/formatting.py b/src/click/formatting.py index 319c7f6..5a8b81c 100644 --- a/src/click/formatting.py +++ b/src/click/formatting.py @@ -91,7 +91,7 @@ def wrap_text( return "\n\n".join(rv) -class HelpFormatter(object): +class HelpFormatter: """This class helps with formatting text-based help pages. It's usually just needed for very special internal cases, but it's also exposed so that developers can write their own fancy outputs. diff --git a/src/click/parser.py b/src/click/parser.py index 95442af..ae486d0 100644 --- a/src/click/parser.py +++ b/src/click/parser.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module started out as largely a copy paste from the stdlib's optparse module with the features removed that we do not need from @@ -84,8 +83,8 @@ def _unpack_args(args, nargs_spec): def _error_opt_args(nargs, opt): if nargs == 1: - raise BadOptionUsage(opt, "{} option requires an argument".format(opt)) - raise BadOptionUsage(opt, "{} option requires {} arguments".format(opt, nargs)) + raise BadOptionUsage(opt, f"{opt} option requires an argument") + raise BadOptionUsage(opt, f"{opt} option requires {nargs} arguments") def split_opt(opt): @@ -123,7 +122,7 @@ def split_arg_string(string): return rv -class Option(object): +class Option: def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None): self._short_opts = [] self._long_opts = [] @@ -132,7 +131,7 @@ class Option(object): for opt in opts: prefix, value = split_opt(opt) if not prefix: - raise ValueError("Invalid start character for option ({})".format(opt)) + raise ValueError(f"Invalid start character for option ({opt})") self.prefixes.add(prefix[0]) if len(prefix) == 1 and len(value) == 1: self._short_opts.append(opt) @@ -165,11 +164,11 @@ class Option(object): elif self.action == "count": state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 else: - raise ValueError("unknown action '{}'".format(self.action)) + raise ValueError(f"unknown action '{self.action}'") state.order.append(self.obj) -class Argument(object): +class Argument: def __init__(self, dest, nargs=1, obj=None): self.dest = dest self.nargs = nargs @@ -182,13 +181,13 @@ class Argument(object): value = None elif holes != 0: raise BadArgumentUsage( - "argument {} takes {} values".format(self.dest, self.nargs) + f"argument {self.dest} takes {self.nargs} values" ) state.opts[self.dest] = value state.order.append(self.obj) -class ParsingState(object): +class ParsingState: def __init__(self, rargs): self.opts = {} self.largs = [] @@ -196,7 +195,7 @@ class ParsingState(object): self.order = [] -class OptionParser(object): +class OptionParser: """The option parser is an internal class that is ultimately used to parse options and arguments. It's modelled after optparse and brings a similar but vastly simplified API. It should generally not be used @@ -348,7 +347,7 @@ class OptionParser(object): del state.rargs[:nargs] elif explicit_value is not None: - raise BadOptionUsage(opt, "{} option does not take a value".format(opt)) + raise BadOptionUsage(opt, f"{opt} option does not take a value") else: value = None diff --git a/src/click/termui.py b/src/click/termui.py index dd51cdf..b9c91c7 100644 --- a/src/click/termui.py +++ b/src/click/termui.py @@ -153,7 +153,7 @@ def prompt( try: result = value_proc(value) except UsageError as e: - echo("Error: {}".format(e.message), err=err) # noqa: B306 + echo(f"Error: {e.message}", err=err) # noqa: B306 continue if not confirmation_prompt: return result @@ -504,12 +504,12 @@ def style( try: bits.append("\033[{}m".format(_ansi_colors[fg])) except KeyError: - raise TypeError("Unknown color '{}'".format(fg)) + raise TypeError(f"Unknown color '{fg}'") if bg: try: bits.append("\033[{}m".format(_ansi_colors[bg] + 10)) except KeyError: - raise TypeError("Unknown color '{}'".format(bg)) + raise TypeError(f"Unknown color '{bg}'") if bold is not None: bits.append("\033[{}m".format(1 if bold else 22)) if dim is not None: diff --git a/src/click/testing.py b/src/click/testing.py index eef3399..717d2e4 100644 --- a/src/click/testing.py +++ b/src/click/testing.py @@ -12,7 +12,7 @@ from . import utils from ._compat import _find_binary_reader -class EchoingStdin(object): +class EchoingStdin: def __init__(self, input, output): self._input = input self._output = output @@ -58,7 +58,7 @@ def make_input_stream(input, charset): return io.BytesIO(input) -class Result(object): +class Result: """Holds the captured result of an invoked CLI script.""" def __init__( @@ -104,7 +104,7 @@ class Result(object): ) -class CliRunner(object): +class CliRunner: """The CLI runner provides functionality to invoke a Click command line script for unittesting purposes in a isolated environment. This only works in single-threaded systems without any concurrency as it changes the @@ -191,7 +191,7 @@ class CliRunner(object): def visible_input(prompt=None): sys.stdout.write(prompt or "") val = input.readline().rstrip("\r\n") - sys.stdout.write("{}\n".format(val)) + sys.stdout.write(f"{val}\n") sys.stdout.flush() return val @@ -261,7 +261,7 @@ class CliRunner(object): env=None, catch_exceptions=True, color=False, - **extra + **extra, ): """Invokes a command in an isolated environment. The arguments are forwarded directly to the command line script, the `extra` keyword @@ -359,5 +359,5 @@ class CliRunner(object): os.chdir(cwd) try: shutil.rmtree(t) - except (OSError, IOError): # noqa: B014 + except OSError: # noqa: B014 pass diff --git a/src/click/types.py b/src/click/types.py index d794235..7aae2fe 100644 --- a/src/click/types.py +++ b/src/click/types.py @@ -12,7 +12,7 @@ from .utils import LazyFile from .utils import safecall -class ParamType(object): +class ParamType: """Helper for converting values through types. The following is necessary for a valid type: @@ -258,7 +258,7 @@ class IntParamType(ParamType): try: return int(value) except ValueError: - self.fail("{} is not a valid integer".format(value), param, ctx) + self.fail(f"{value} is not a valid integer", param, ctx) def __repr__(self): return "INT" @@ -320,7 +320,7 @@ class IntRange(IntParamType): return rv def __repr__(self): - return "IntRange({}, {})".format(self.min, self.max) + return f"IntRange({self.min}, {self.max})" class FloatParamType(ParamType): @@ -330,9 +330,7 @@ class FloatParamType(ParamType): try: return float(value) except ValueError: - self.fail( - "{} is not a valid floating point value".format(value), param, ctx - ) + self.fail(f"{value} is not a valid floating point value", param, ctx) def __repr__(self): return "FLOAT" @@ -394,7 +392,7 @@ class FloatRange(FloatParamType): return rv def __repr__(self): - return "FloatRange({}, {})".format(self.min, self.max) + return f"FloatRange({self.min}, {self.max})" class BoolParamType(ParamType): @@ -408,7 +406,7 @@ class BoolParamType(ParamType): return True elif value in ("false", "f", "0", "no", "n"): return False - self.fail("{} is not a valid boolean".format(value), param, ctx) + self.fail(f"{value} is not a valid boolean", param, ctx) def __repr__(self): return "BOOL" @@ -423,7 +421,7 @@ class UUIDParameterType(ParamType): try: return uuid.UUID(value) except ValueError: - self.fail("{} is not a valid UUID value".format(value), param, ctx) + self.fail(f"{value} is not a valid UUID value", param, ctx) def __repr__(self): return "UUID" @@ -506,7 +504,7 @@ class File(ParamType): else: ctx.call_on_close(safecall(f.flush)) return f - except (IOError, OSError) as e: # noqa: B014 + except OSError as e: # noqa: B014 self.fail( "Could not open file: {}: {}".format( filename_to_ui(value), get_strerror(e) @@ -713,7 +711,7 @@ def convert_type(ty, default=None): try: if issubclass(ty, ParamType): raise AssertionError( - "Attempted to use an uninstantiated parameter type ({}).".format(ty) + f"Attempted to use an uninstantiated parameter type ({ty})." ) except TypeError: pass diff --git a/src/click/utils.py b/src/click/utils.py index 0f634bb..b18c83d 100644 --- a/src/click/utils.py +++ b/src/click/utils.py @@ -72,7 +72,7 @@ def make_default_short_help(help, max_length=45): return "".join(result) -class LazyFile(object): +class LazyFile: """A lazy file works like a regular file but it does not fully open the file but it does perform some basic checks early to see if the filename parameter does make sense. This is useful for safely opening @@ -105,7 +105,7 @@ class LazyFile(object): def __repr__(self): if self._f is not None: return repr(self._f) - return "<unopened file '{}' {}>".format(self.name, self.mode) + return f"<unopened file '{self.name}' {self.mode}>" def open(self): """Opens the file if it's not yet open. This call might fail with @@ -118,7 +118,7 @@ class LazyFile(object): rv, self.should_close = open_stream( self.name, self.mode, self.encoding, self.errors, atomic=self.atomic ) - except (IOError, OSError) as e: # noqa: E402 + except OSError as e: # noqa: E402 from .exceptions import FileError raise FileError(self.name, hint=get_strerror(e)) @@ -148,7 +148,7 @@ class LazyFile(object): return iter(self._f) -class KeepOpenFile(object): +class KeepOpenFile: def __init__(self, file): self._file = file @@ -226,9 +226,9 @@ def echo(message=None, file=None, nl=True, err=False, color=None): message = str(message) if nl: - message = message or u"" + message = message or "" if isinstance(message, str): - message += u"\n" + message += "\n" else: message += b"\n" @@ -276,7 +276,7 @@ def get_binary_stream(name): """ opener = binary_streams.get(name) if opener is None: - raise TypeError("Unknown standard stream '{}'".format(name)) + raise TypeError(f"Unknown standard stream '{name}'") return opener() @@ -293,7 +293,7 @@ def get_text_stream(name, encoding=None, errors="strict"): """ opener = text_streams.get(name) if opener is None: - raise TypeError("Unknown standard stream '{}'".format(name)) + raise TypeError(f"Unknown standard stream '{name}'") return opener(encoding, errors) @@ -419,7 +419,7 @@ def get_app_dir(app_name, roaming=True, force_posix=False): ) -class PacifyFlushWrapper(object): +class PacifyFlushWrapper: """This wrapper is used to catch and suppress BrokenPipeErrors resulting from ``.flush()`` being called on broken pipe during the shutdown/final-GC of the Python interpreter. Notably ``.flush()`` is always called on @@ -434,7 +434,7 @@ class PacifyFlushWrapper(object): def flush(self): try: self.wrapped.flush() - except IOError as e: + except OSError as e: import errno if e.errno != errno.EPIPE: diff --git a/tests/test_arguments.py b/tests/test_arguments.py index bb580fc..4970486 100644 --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import sys import pytest @@ -12,7 +11,7 @@ def test_nargs_star(runner): @click.argument("dst") def copy(src, dst): click.echo("src={}".format("|".join(src))) - click.echo("dst={}".format(dst)) + click.echo(f"dst={dst}") result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"]) assert not result.exception @@ -33,7 +32,7 @@ def test_nargs_tup(runner): @click.argument("name", nargs=1) @click.argument("point", nargs=2, type=click.INT) def copy(name, point): - click.echo("name={}".format(name)) + click.echo(f"name={name}") click.echo("point={0[0]}/{0[1]}".format(point)) result = runner.invoke(copy, ["peter", "1", "2"]) @@ -91,7 +90,7 @@ def test_bytes_args(runner, monkeypatch): runner.invoke( from_bytes, - [u"Something outside of ASCII range: 林".encode("UTF-8")], + ["Something outside of ASCII range: 林".encode()], catch_exceptions=False, ) @@ -208,7 +207,7 @@ def test_missing_arg(runner): @click.command() @click.argument("arg") def cmd(arg): - click.echo("arg:{}".format(arg)) + click.echo(f"arg:{arg}") result = runner.invoke(cmd, []) assert result.exit_code == 2 diff --git a/tests/test_bashcomplete.py b/tests/test_bashcomplete.py index df4ef28..f48927a 100644 --- a/tests/test_bashcomplete.py +++ b/tests/test_bashcomplete.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import pytest import click diff --git a/tests/test_basic.py b/tests/test_basic.py index f07b6d1..9f9d71e 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import os import uuid @@ -82,7 +81,7 @@ def test_basic_option(runner): @click.command() @click.option("--foo", default="no value") def cli(foo): - click.echo(u"FOO:[{}]".format(foo)) + click.echo(f"FOO:[{foo}]") result = runner.invoke(cli, []) assert not result.exception @@ -100,9 +99,9 @@ def test_basic_option(runner): assert not result.exception assert "FOO:[]" in result.output - result = runner.invoke(cli, [u"--foo=\N{SNOWMAN}"]) + result = runner.invoke(cli, ["--foo=\N{SNOWMAN}"]) assert not result.exception - assert u"FOO:[\N{SNOWMAN}]" in result.output + assert "FOO:[\N{SNOWMAN}]" in result.output def test_int_option(runner): @@ -131,7 +130,7 @@ def test_uuid_option(runner): ) def cli(u): assert type(u) is uuid.UUID - click.echo("U:[{}]".format(u)) + click.echo(f"U:[{u}]") result = runner.invoke(cli, []) assert not result.exception @@ -151,7 +150,7 @@ def test_float_option(runner): @click.option("--foo", default=42, type=click.FLOAT) def cli(foo): assert type(foo) is float - click.echo("FOO:[{}]".format(foo)) + click.echo(f"FOO:[{foo}]") result = runner.invoke(cli, []) assert not result.exception @@ -182,7 +181,7 @@ def test_boolean_option(runner): assert result.output == "False\n" result = runner.invoke(cli, []) assert not result.exception - assert result.output == "{}\n".format(default) + assert result.output == f"{default}\n" for default in True, False: @@ -196,7 +195,7 @@ def test_boolean_option(runner): assert result.output == "{}\n".format(not default) result = runner.invoke(cli, []) assert not result.exception - assert result.output == "{}\n".format(default) + assert result.output == f"{default}\n" def test_boolean_conversion(runner): @@ -219,7 +218,7 @@ def test_boolean_conversion(runner): result = runner.invoke(cli, []) assert not result.exception - assert result.output == "{}\n".format(default) + assert result.output == f"{default}\n" def test_file_option(runner): diff --git a/tests/test_chain.py b/tests/test_chain.py index c227270..cf9b198 100644 --- a/tests/test_chain.py +++ b/tests/test_chain.py @@ -77,12 +77,12 @@ def test_chaining_with_options(runner): @cli.command("sdist") @click.option("--format") def sdist(format): - click.echo("sdist called {}".format(format)) + click.echo(f"sdist called {format}") @cli.command("bdist") @click.option("--format") def bdist(format): - click.echo("bdist called {}".format(format)) + click.echo(f"bdist called {format}") result = runner.invoke(cli, ["bdist", "--format=1", "sdist", "--format=2"]) assert not result.exception @@ -97,12 +97,12 @@ def test_chaining_with_arguments(runner): @cli.command("sdist") @click.argument("format") def sdist(format): - click.echo("sdist called {}".format(format)) + click.echo(f"sdist called {format}") @cli.command("bdist") @click.argument("format") def bdist(format): - click.echo("bdist called {}".format(format)) + click.echo(f"bdist called {format}") result = runner.invoke(cli, ["bdist", "1", "sdist", "2"]) assert not result.exception @@ -192,7 +192,7 @@ def test_multicommand_arg_behavior(runner): @click.group(chain=True) @click.argument("arg") def cli(arg): - click.echo("cli:{}".format(arg)) + click.echo(f"cli:{arg}") @cli.command() def a(): diff --git a/tests/test_commands.py b/tests/test_commands.py index 1d99218..1e19746 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import re import click @@ -26,7 +25,7 @@ def test_other_command_forward(runner): @cli.command() @click.option("--count", default=1) def test(count): - click.echo("Count: {:d}".format(count)) + click.echo(f"Count: {count:d}") @cli.command() @click.option("--count", default=1) @@ -102,7 +101,7 @@ def test_group_with_args(runner): @click.group() @click.argument("obj") def cli(obj): - click.echo("obj={}".format(obj)) + click.echo(f"obj={obj}") @cli.command() def move(): @@ -264,7 +263,7 @@ def test_unprocessed_options(runner): @click.argument("args", nargs=-1, type=click.UNPROCESSED) @click.option("--verbose", "-v", count=True) def cli(verbose, args): - click.echo("Verbosity: {}".format(verbose)) + click.echo(f"Verbosity: {verbose}") click.echo("Args: {}".format("|".join(args))) result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"]) diff --git a/tests/test_compat.py b/tests/test_compat.py index 26647ba..3c458e9 100644 --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -23,7 +23,7 @@ def test_zsh_func_name(): @pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows") def test_is_jupyter_kernel_output(): - class JupyterKernelFakeStream(object): + class JupyterKernelFakeStream: pass # implementation detail, aka cheapskate test diff --git a/tests/test_context.py b/tests/test_context.py index 06cc907..44befa5 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import pytest import click @@ -6,7 +5,7 @@ from click.core import ParameterSource def test_ensure_context_objects(runner): - class Foo(object): + class Foo: def __init__(self): self.title = "default" @@ -28,7 +27,7 @@ def test_ensure_context_objects(runner): def test_get_context_objects(runner): - class Foo(object): + class Foo: def __init__(self): self.title = "default" @@ -51,7 +50,7 @@ def test_get_context_objects(runner): def test_get_context_objects_no_ensuring(runner): - class Foo(object): + class Foo: def __init__(self): self.title = "default" @@ -74,7 +73,7 @@ def test_get_context_objects_no_ensuring(runner): def test_get_context_objects_missing(runner): - class Foo(object): + class Foo: pass pass_foo = click.make_pass_decorator(Foo) @@ -132,7 +131,7 @@ def test_global_context_object(runner): def test_context_meta(runner): - LANG_KEY = "{}.lang".format(__name__) + LANG_KEY = f"{__name__}.lang" def set_language(value): click.get_current_context().meta[LANG_KEY] = value @@ -219,7 +218,7 @@ def test_make_pass_decorator_args(runner): invocation order. """ - class Foo(object): + class Foo: title = "foocmd" pass_foo = click.make_pass_decorator(Foo) diff --git a/tests/test_defaults.py b/tests/test_defaults.py index ce44903..d55b1f4 100644 --- a/tests/test_defaults.py +++ b/tests/test_defaults.py @@ -6,7 +6,7 @@ def test_basic_defaults(runner): @click.option("--foo", default=42, type=click.FLOAT) def cli(foo): assert type(foo) is float - click.echo("FOO:[{}]".format(foo)) + click.echo(f"FOO:[{foo}]") result = runner.invoke(cli, []) assert not result.exception diff --git a/tests/test_formatting.py b/tests/test_formatting.py index 4fabbb2..b2f72b7 100644 --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import click @@ -151,7 +150,7 @@ def test_formatting_usage_error(runner): @click.command() @click.argument("arg") def cmd(arg): - click.echo("arg:{}".format(arg)) + click.echo(f"arg:{arg}") result = runner.invoke(cmd, []) assert result.exit_code == 2 @@ -208,7 +207,7 @@ def test_formatting_usage_error_nested(runner): @cmd.command() @click.argument("bar") def foo(bar): - click.echo("foo:{}".format(bar)) + click.echo(f"foo:{bar}") result = runner.invoke(cmd, ["foo"]) assert result.exit_code == 2 @@ -224,7 +223,7 @@ def test_formatting_usage_error_no_help(runner): @click.command(add_help_option=False) @click.argument("arg") def cmd(arg): - click.echo("arg:{}".format(arg)) + click.echo(f"arg:{arg}") result = runner.invoke(cmd, []) assert result.exit_code == 2 @@ -239,7 +238,7 @@ def test_formatting_usage_custom_help(runner): @click.command(context_settings=dict(help_option_names=["--man"])) @click.argument("arg") def cmd(arg): - click.echo("arg:{}".format(arg)) + click.echo(f"arg:{arg}") result = runner.invoke(cmd, []) assert result.exit_code == 2 diff --git a/tests/test_options.py b/tests/test_options.py index 3eea5e6..95cdad5 100644 --- a/tests/test_options.py +++ b/tests/test_options.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import os import re @@ -12,7 +11,7 @@ def test_prefixes(runner): @click.option("++foo", is_flag=True, help="das foo") @click.option("--bar", is_flag=True, help="das bar") def cli(foo, bar): - click.echo("foo={} bar={}".format(foo, bar)) + click.echo(f"foo={foo} bar={bar}") result = runner.invoke(cli, ["++foo", "--bar"]) assert not result.exception @@ -57,7 +56,7 @@ def test_counting(runner): @click.command() @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3)) def cli(v): - click.echo("verbosity={:d}".format(v)) + click.echo(f"verbosity={v:d}") result = runner.invoke(cli, ["-vvv"]) assert not result.exception @@ -86,7 +85,7 @@ def test_unknown_options(runner, unknown_flag): result = runner.invoke(cli, [unknown_flag]) assert result.exception - assert "no such option: {}".format(unknown_flag) in result.output + assert f"no such option: {unknown_flag}" in result.output def test_multiple_required(runner): @@ -108,7 +107,7 @@ def test_empty_envvar(runner): @click.command() @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH") def cli(mypath): - click.echo("mypath: {}".format(mypath)) + click.echo(f"mypath: {mypath}") result = runner.invoke(cli, [], env={"MYPATH": ""}) assert result.exit_code == 0 @@ -145,7 +144,7 @@ def test_multiple_envvar(runner): cmd, [], auto_envvar_prefix="TEST", - env={"TEST_ARG": "foo{}bar".format(os.path.pathsep)}, + env={"TEST_ARG": f"foo{os.path.pathsep}bar"}, ) assert not result.exception assert result.output == "foo|bar\n" diff --git a/tests/test_termui.py b/tests/test_termui.py index 003a269..616ab7d 100644 --- a/tests/test_termui.py +++ b/tests/test_termui.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import time import pytest @@ -7,7 +6,7 @@ import click._termui_impl from click._compat import WIN -class FakeClock(object): +class FakeClock: def __init__(self): self.now = time.time() @@ -42,7 +41,7 @@ def test_progressbar_strip_regression(runner, monkeypatch): def test_progressbar_length_hint(runner, monkeypatch): - class Hinted(object): + class Hinted: def __init__(self, n): self.items = list(range(n)) @@ -123,7 +122,7 @@ def test_progressbar_format_pos(runner, pos, length): with _create_progress(length, length_known=length != 0, pos=pos) as progress: result = progress.format_pos() if progress.length_known: - assert result == "{}/{}".format(pos, length) + assert result == f"{pos}/{length}" else: assert result == str(pos) @@ -291,7 +290,7 @@ def test_progressbar_item_show_func(runner, monkeypatch): @click.command() def cli(): with click.progressbar( - range(4), item_show_func=lambda x: "Custom {}".format(x) + range(4), item_show_func=lambda x: f"Custom {x}" ) as progress: for _ in progress: fake_clock.advance_time() @@ -315,7 +314,7 @@ def test_progressbar_update_with_item_show_func(runner, monkeypatch): @click.command() def cli(): with click.progressbar( - length=6, item_show_func=lambda x: "Custom {}".format(x) + length=6, item_show_func=lambda x: f"Custom {x}" ) as progress: while not progress.finished: fake_clock.advance_time() @@ -333,7 +332,7 @@ def test_progressbar_update_with_item_show_func(runner, monkeypatch): assert "Custom 4" in lines[2] -@pytest.mark.parametrize("key_char", (u"h", u"H", u"é", u"À", u" ", u"字", u"àH", u"àR")) +@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR")) @pytest.mark.parametrize("echo", [True, False]) @pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.") def test_getchar_windows(runner, monkeypatch, key_char, echo): @@ -344,7 +343,7 @@ def test_getchar_windows(runner, monkeypatch, key_char, echo): @pytest.mark.parametrize( - "special_key_char, key_char", [(u"\x00", "a"), (u"\x00", "b"), (u"\xe0", "c")] + "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")] ) @pytest.mark.skipif( not WIN, reason="Tests special character inputs using the msvcrt module." @@ -359,7 +358,7 @@ def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_ @pytest.mark.parametrize( - ("key_char", "exc"), [(u"\x03", KeyboardInterrupt), (u"\x1a", EOFError)], + ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)], ) @pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.") def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc): diff --git a/tests/test_testing.py b/tests/test_testing.py index 99701b5..5b2c813 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -59,7 +59,7 @@ def test_prompts(): @click.command() @click.option("--foo", prompt=True) def test(foo): - click.echo("foo={}".format(foo)) + click.echo(f"foo={foo}") runner = CliRunner() result = runner.invoke(test, input="wau wau\n") @@ -69,7 +69,7 @@ def test_prompts(): @click.command() @click.option("--foo", prompt=True, hide_input=True) def test(foo): - click.echo("foo={}".format(foo)) + click.echo(f"foo={foo}") runner = CliRunner() result = runner.invoke(test, input="wau wau\n") diff --git a/tests/test_utils.py b/tests/test_utils.py index 2ca1a8a..bf3956d 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -12,7 +12,7 @@ from click._compat import WIN def test_echo(runner): with runner.isolation() as outstreams: - click.echo(u"\N{SNOWMAN}") + click.echo("\N{SNOWMAN}") click.echo(b"\x44\x44") click.echo(42, nl=False) click.echo(b"a", nl=False) @@ -38,8 +38,8 @@ def test_echo_custom_file(): import io f = io.StringIO() - click.echo(u"hello", file=f) - assert f.getvalue() == u"hello\n" + click.echo("hello", file=f) + assert f.getvalue() == "hello\n" @pytest.mark.parametrize( @@ -80,14 +80,12 @@ def test_unstyle_other_ansi(text, expect): def test_filename_formatting(): assert click.format_filename(b"foo.txt") == "foo.txt" assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt" - assert click.format_filename(u"/x/foo.txt") == "/x/foo.txt" - assert click.format_filename(u"/x/foo.txt", shorten=True) == "foo.txt" + assert click.format_filename("/x/foo.txt") == "/x/foo.txt" + assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt" # filesystem encoding on windows permits this. if not WIN: - assert ( - click.format_filename(b"/x/foo\xff.txt", shorten=True) == u"foo\ufffd.txt" - ) + assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\ufffd.txt" def test_prompts(runner): @@ -192,21 +190,21 @@ def test_echo_color_flag(monkeypatch, capfd): click.echo(styled_text, color=False) out, err = capfd.readouterr() - assert out == "{}\n".format(text) + assert out == f"{text}\n" click.echo(styled_text, color=True) out, err = capfd.readouterr() - assert out == "{}\n".format(styled_text) + assert out == f"{styled_text}\n" isatty = True click.echo(styled_text) out, err = capfd.readouterr() - assert out == "{}\n".format(styled_text) + assert out == f"{styled_text}\n" isatty = False click.echo(styled_text) out, err = capfd.readouterr() - assert out == "{}\n".format(text) + assert out == f"{text}\n" @pytest.mark.skipif(WIN, reason="Test too complex to make work windows.") |
