summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorDavid Lord <davidism@gmail.com>2020-04-19 22:22:49 -0700
committerDavid Lord <davidism@gmail.com>2020-04-20 07:12:52 -0700
commitb444e6355ec50417546f42138bb833d1e9e8b306 (patch)
tree08b29d284fa7348c591aba0bbc71a21da7709876 /src
parent62f84aa3242d6d9f57243b941b013b2536ea3b9c (diff)
downloadclick-b444e6355ec50417546f42138bb833d1e9e8b306.tar.gz
apply pyupgrade --py36-plus
Diffstat (limited to 'src')
-rw-r--r--src/click/_bashcomplete.py2
-rw-r--r--src/click/_compat.py8
-rw-r--r--src/click/_termui_impl.py30
-rw-r--r--src/click/_winconsole.py9
-rw-r--r--src/click/core.py44
-rw-r--r--src/click/exceptions.py20
-rw-r--r--src/click/formatting.py2
-rw-r--r--src/click/parser.py21
-rw-r--r--src/click/termui.py6
-rw-r--r--src/click/testing.py12
-rw-r--r--src/click/types.py20
-rw-r--r--src/click/utils.py20
12 files changed, 93 insertions, 101 deletions
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: