enable deferred evaluation of annotations
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Brian Grohe · committed by David Lord · parent 988c683 · Browse files · 18 files·+176 added−140 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+176 added−140 removed
- tests:+1 added−0 removed
- other:+175 added−140 removed
Provenance
- Commit
ecdeb0c- Tree
6d54424- Author
Brian Grohe <grohe43@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
988c683
18 files changed+176 added−140 removed
modified:src/click/__init__.py+2 added
2 unmodified lines3 writing command line scripts fun. Unlike other modules, it's based4 around a simple API that does not come with too much magic and is5 composable.6 """7+from __future__ import annotations8+9 from .core import Argument as Argument10 from .core import Command as Command11 from .core import CommandCollection as CommandCollection12 from .core import Context as Context99 unmodified linesmodified:src/click/_compat.py+5 added-3 removed
1+from __future__ import annotations2+3 import codecs4 import io5 import os6 import re352 unmodified lines359 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)360 361 362 def _wrap_io_open(361- file: t.Union[str, "os.PathLike[str]", int],363+ file: t.Union[str, os.PathLike[str], int],364 mode: str,365 encoding: t.Optional[str],366 errors: t.Optional[str],367 ) -> t.IO[t.Any]:4 unmodified lines372 return open(file, mode, encoding=encoding, errors=errors)373 374 375 def open_stream(374- filename: "t.Union[str, os.PathLike[str]]",376+ filename: t.Union[str, os.PathLike[str]],377 mode: str = "r",378 encoding: t.Optional[str] = None,379 errors: t.Optional[str] = "strict",380 atomic: bool = False,92 unmodified lines473 474 def __getattr__(self, name: str) -> t.Any:475 return getattr(self._f, name)476 475- def __enter__(self) -> "_AtomicFile":477+ def __enter__(self) -> _AtomicFile:478 return self479 480 def __exit__(self, exc_type: t.Optional[t.Type[BaseException]], *_: t.Any) -> None:481 self.close(delete=exc_type is not None)144 unmodified linesmodified:src/click/_termui_impl.py+3 added-1 removed
1 unmodified line2 This module contains implementations for the termui module. To keep the3 import time of Click down, some infrequently used functionality is4 placed in this module and only imported as needed.5 """6+from __future__ import annotations7+8 import contextlib9 import math10 import os11 import sys93 unmodified lines105 self.current_item: t.Optional[V] = None106 self.is_hidden: bool = not isatty(self.file)107 self._last_line: t.Optional[str] = None108 107- def __enter__(self) -> "ProgressBar[V]":109+ def __enter__(self) -> ProgressBar[V]:110 self.entered = True111 self.render_progress()112 return self113 628 unmodified linesmodified:src/click/_textwrap.py+2 added
1+from __future__ import annotations2+3 import textwrap4 import typing as t5 from contextlib import contextmanager6 45 unmodified linesmodified:src/click/_winconsole.py+2 added
4 unmodified lines5 # There are some general differences in regards to how this works6 # compared to the original patches as we do not need to patch7 # the entire interpreter but just work in our little world of8 # echo and prompt.9+from __future__ import annotations10+11 import io12 import sys13 import time14 import typing as t267 unmodified linesmodified:src/click/core.py+49 added-47 removed
1+from __future__ import annotations2+3 import enum4 import errno5 import inspect6 import os40 unmodified lines47 V = t.TypeVar("V")48 49 50 def _complete_visible_commands(49- ctx: "Context", incomplete: str50-) -> t.Iterator[t.Tuple[str, "Command"]]:51+ ctx: Context, incomplete: str52+) -> t.Iterator[t.Tuple[str, Command]]:53 """List all the subcommands of a group that start with the54 incomplete value and aren't hidden.55 56 :param ctx: Invocation context for the group.9 unmodified lines66 yield name, command67 68 69 def _check_nested_chain(68- base_command: "Group", cmd_name: str, cmd: "Command", register: bool = False70+ base_command: Group, cmd_name: str, cmd: Command, register: bool = False71 ) -> None:72 if not base_command.chain or not isinstance(cmd, Group):73 return74 16 unmodified lines91 92 93 @contextmanager94 def augment_usage_errors(93- ctx: "Context", param: t.Optional["Parameter"] = None95+ ctx: Context, param: t.Optional[Parameter] = None96 ) -> t.Iterator[None]:97 """Context manager that attaches extra information to exceptions."""98 try:99 yield9 unmodified lines109 raise110 111 112 def iter_params_for_processing(111- invocation_order: t.Sequence["Parameter"],112- declaration_order: t.Sequence["Parameter"],113-) -> t.List["Parameter"]:113+ invocation_order: t.Sequence[Parameter],114+ declaration_order: t.Sequence[Parameter],115+) -> t.List[Parameter]:116 """Given a sequence of parameters in the order as should be considered117 for processing and an iterable of parameters that exist, this returns118 a list in the correct order as they should be processed.119 """120 119- def sort_key(item: "Parameter") -> t.Tuple[bool, float]:121+ def sort_key(item: Parameter) -> t.Tuple[bool, float]:122 try:123 idx: float = invocation_order.index(item)124 except ValueError:125 idx = float("inf")130 unmodified lines256 257 #: The formatter class to create with :meth:`make_formatter`.258 #:259 #: .. versionadded:: 8.0258- formatter_class: t.Type["HelpFormatter"] = HelpFormatter260+ formatter_class: t.Type[HelpFormatter] = HelpFormatter261 262 def __init__(263 self,262- command: "Command",263- parent: t.Optional["Context"] = None,264+ command: Command,265+ parent: t.Optional[Context] = None,266 info_name: t.Optional[str] = None,267 obj: t.Optional[t.Any] = None,268 auto_envvar_prefix: t.Optional[str] = None,269 default_map: t.Optional[t.MutableMapping[str, t.Any]] = None,193 unmodified lines463 "ignore_unknown_options": self.ignore_unknown_options,464 "auto_envvar_prefix": self.auto_envvar_prefix,465 }466 465- def __enter__(self) -> "Context":467+ def __enter__(self) -> Context:468 self._depth += 1469 push_context(self)470 return self471 8 unmodified lines480 self.close()481 pop_context()482 483 @contextmanager482- def scope(self, cleanup: bool = True) -> t.Iterator["Context"]:484+ def scope(self, cleanup: bool = True) -> t.Iterator[Context]:485 """This helper method can be used with the context object to promote486 it to the current thread local (see :func:`get_current_context`).487 The default behavior of this is to invoke the cleanup functions which488 can be disabled by setting `cleanup` to `False`. The cleanup139 unmodified lines628 629 rv = f"{' '.join(parent_command_path)} {rv}"630 return rv.lstrip()631 630- def find_root(self) -> "Context":632+ def find_root(self) -> Context:633 """Finds the outermost context."""634 node = self635 while node.parent is not None:636 node = node.parent637 return node638 639 def find_object(self, object_type: t.Type[V]) -> t.Optional[V]:640 """Finds the closest object of a given type."""639- node: t.Optional["Context"] = self641+ node: t.Optional[Context] = self642 643 while node is not None:644 if isinstance(node.obj, object_type):645 return node.obj12 unmodified lines658 return rv659 660 @t.overload661 def lookup_default(660- self, name: str, call: "te.Literal[True]" = True662+ self, name: str, call: te.Literal[True] = True663 ) -> t.Optional[t.Any]:664 ...665 666 @t.overload667 def lookup_default(666- self, name: str, call: "te.Literal[False]" = ...668+ self, name: str, call: te.Literal[False] = ...669 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:670 ...671 672 def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]:15 unmodified lines688 return value689 690 return None691 690- def fail(self, message: str) -> "te.NoReturn":692+ def fail(self, message: str) -> te.NoReturn:693 """Aborts the execution of the program with a specific error694 message.695 696 :param message: the error message to fail with.697 """698 raise UsageError(message, self)699 698- def abort(self) -> "te.NoReturn":700+ def abort(self) -> te.NoReturn:701 """Aborts the script."""702 raise Abort()703 702- def exit(self, code: int = 0) -> "te.NoReturn":704+ def exit(self, code: int = 0) -> te.NoReturn:705 """Exits the application with a given exit code."""706 raise Exit(code)707 708 def get_usage(self) -> str:7 unmodified lines716 context and command.717 """718 return self.command.get_help(self)719 718- def _make_sub_context(self, command: "Command") -> "Context":720+ def _make_sub_context(self, command: Command) -> Context:721 """Create a new context of the same type as this context, but722 for a new command.723 724 :meta private:2 unmodified lines727 728 @t.overload729 def invoke(730 __self, # noqa: B902729- __callback: "t.Callable[..., V]",731+ __callback: t.Callable[..., V],732 *args: t.Any,733 **kwargs: t.Any,734 ) -> V:735 ...736 737 @t.overload738 def invoke(739 __self, # noqa: B902738- __callback: "Command",740+ __callback: Command,741 *args: t.Any,742 **kwargs: t.Any,743 ) -> t.Any:744 ...745 746 def invoke(747 __self, # noqa: B902746- __callback: t.Union["Command", "t.Callable[..., V]"],748+ __callback: t.Union[Command, t.Callable[..., V]],749 *args: t.Any,750 **kwargs: t.Any,751 ) -> t.Union[t.Any, V]:752 """Invokes a command callback in exactly the way it expects. There43 unmodified lines796 with ctx:797 return __callback(*args, **kwargs)798 799 def forward(798- __self, __cmd: "Command", *args: t.Any, **kwargs: t.Any # noqa: B902800+ __self, __cmd: Command, *args: t.Any, **kwargs: t.Any # noqa: B902801 ) -> t.Any:802 """Similar to :meth:`invoke` but fills in default keyword803 arguments from the current context if the other command expects804 it. This cannot invoke callbacks directly, only other commands.103 unmodified lines908 self,909 name: t.Optional[str],910 context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,911 callback: t.Optional[t.Callable[..., t.Any]] = None,910- params: t.Optional[t.List["Parameter"]] = None,912+ params: t.Optional[t.List[Parameter]] = None,913 help: t.Optional[str] = None,914 epilog: t.Optional[str] = None,915 short_help: t.Optional[str] = None,916 options_metavar: t.Optional[str] = "[OPTIONS]",19 unmodified lines936 self.callback = callback937 #: the list of parameters for this command in the order they938 #: should show up in the help page and execute. Eager parameters939 #: will automatically be handled before non eager ones.938- self.params: t.List["Parameter"] = params or []940+ self.params: t.List[Parameter] = params or []941 self.help = help942 self.epilog = epilog943 self.options_metavar = options_metavar944 self.short_help = short_help24 unmodified lines969 formatter = ctx.make_formatter()970 self.format_usage(ctx, formatter)971 return formatter.getvalue().rstrip("\n")972 971- def get_params(self, ctx: Context) -> t.List["Parameter"]:973+ def get_params(self, ctx: Context) -> t.List[Parameter]:974 rv = self.params975 help_option = self.get_help_option(ctx)976 977 if help_option is not None:27 unmodified lines1005 all_names.difference_update(param.opts)1006 all_names.difference_update(param.secondary_opts)1007 return list(all_names)1008 1007- def get_help_option(self, ctx: Context) -> t.Optional["Option"]:1009+ def get_help_option(self, ctx: Context) -> t.Optional[Option]:1010 """Returns the help option object."""1011 help_options = self.get_help_option_names(ctx)1012 1013 if not help_options or not self.add_help_option:1014 return None1015 1014- def show_help(ctx: Context, param: "Parameter", value: str) -> None:1016+ def show_help(ctx: Context, param: Parameter, value: str) -> None:1017 if value and not ctx.resilient_parsing:1018 echo(ctx.get_help(), color=ctx.color)1019 ctx.exit()1020 166 unmodified lines1187 1188 if self.callback is not None:1189 return ctx.invoke(self.callback, **ctx.params)1190 1189- def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1191+ def shell_complete(self, ctx: Context, incomplete: str) -> t.List[CompletionItem]:1192 """Return a list of completions for the incomplete value. Looks1193 at the names of options and chained multi-commands.1194 1195 Any command could be part of a chained multi-command, so sibling5 unmodified lines1201 .. versionadded:: 8.01202 """1203 from click.shell_completion import CompletionItem1204 1203- results: t.List["CompletionItem"] = []1205+ results: t.List[CompletionItem] = []1206 1207 if incomplete and not incomplete[0].isalnum():1208 for param in self.get_params(ctx):1209 if (30 unmodified lines1240 self,1241 args: t.Optional[t.Sequence[str]] = None,1242 prog_name: t.Optional[str] = None,1243 complete_var: t.Optional[str] = None,1242- standalone_mode: "te.Literal[True]" = True,1244+ standalone_mode: t.Literal[True] = True,1245 **extra: t.Any,1244- ) -> "te.NoReturn":1246+ ) -> t.NoReturn:1247 ...1248 1249 @t.overload1250 def main(220 unmodified lines1471 #: default class. This makes a custom group class continue to make1472 #: custom groups.1473 #:1474 #: .. versionadded:: 8.01473- group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None1475+ group_class: t.Optional[t.Union[t.Type[Group], t.Type[type]]] = None1476 # Literal[type] isn't valid, so use Type[type]1477 1478 def __init__(1479 self,122 unmodified lines1602 1603 return decorator1604 1605 @t.overload1604- def group(self, __func: t.Callable[..., t.Any]) -> "Group":1606+ def group(self, __func: t.Callable[..., t.Any]) -> Group:1607 ...1608 1609 @t.overload1610 def group(1611 self, *args: t.Any, **kwargs: t.Any1610- ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1612+ ) -> t.Callable[[t.Callable[..., t.Any]], Group]:1613 ...1614 1615 def group(1616 self, *args: t.Any, **kwargs: t.Any1615- ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]:1617+ ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Group], Group]:1618 """A shortcut decorator for declaring and attaching a group to1619 the group. This takes the same arguments as :func:`group` and1620 immediately registers the created group with this group by1621 calling :meth:`add_command`.23 unmodified lines1645 kwargs["cls"] = type(self)1646 else:1647 kwargs["cls"] = self.group_class1648 1647- def decorator(f: t.Callable[..., t.Any]) -> "Group":1649+ def decorator(f: t.Callable[..., t.Any]) -> Group:1650 cmd: Group = group(*args, **kwargs)(f)1651 self.add_command(cmd)1652 return cmd1653 203 unmodified lines1857 self.parse_args(ctx, ctx.args)1858 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1859 return cmd_name if cmd else None, cmd, args[1:]1860 1859- def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1861+ def shell_complete(self, ctx: Context, incomplete: str) -> t.List[CompletionItem]:1862 """Return a list of completions for the incomplete value. Looks1863 at the names of options, subcommands, and chained1864 multi-commands.1865 166 unmodified lines2032 param_decls: t.Optional[t.Sequence[str]] = None,2033 type: t.Optional[t.Union[types.ParamType, t.Any]] = None,2034 required: bool = False,2035 default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None,2034- callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None,2036+ callback: t.Optional[t.Callable[[Context, Parameter, t.Any], t.Any]] = None,2037 nargs: t.Optional[int] = None,2038 multiple: bool = False,2039 metavar: t.Optional[str] = None,2040 expose_value: bool = True,2041 is_eager: bool = False,2042 envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None,2043 shell_complete: t.Optional[2044 t.Callable[2043- [Context, "Parameter", str],2044- t.Union[t.List["CompletionItem"], t.List[str]],2045+ [Context, Parameter, str],2046+ t.Union[t.List[CompletionItem], t.List[str]],2047 ]2048 ] = None,2049 ) -> None:2050 self.name: t.Optional[str]116 unmodified lines2167 return metavar2168 2169 @t.overload2170 def get_default(2169- self, ctx: Context, call: "te.Literal[True]" = True2171+ self, ctx: Context, call: te.Literal[True] = True2172 ) -> t.Optional[t.Any]:2173 ...2174 2175 @t.overload187 unmodified lines2363 """2364 hint_list = self.opts or [self.human_readable_name]2365 return " / ".join(f"'{x}'" for x in hint_list)2366 2365- def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:2367+ def shell_complete(self, ctx: Context, incomplete: str) -> t.List[CompletionItem]:2368 """Return a list of completions for the incomplete value. If a2369 ``shell_complete`` function was given during init, it is used.2370 Otherwise, the :attr:`type`2371 :meth:`~click.types.ParamType.shell_complete` function is used.410 unmodified lines2782 return ("; " if any_prefix_is_slash else " / ").join(rv), help2783 2784 @t.overload2785 def get_default(2784- self, ctx: Context, call: "te.Literal[True]" = True2786+ self, ctx: Context, call: te.Literal[True] = True2787 ) -> t.Optional[t.Any]:2788 ...2789 2790 @t.overload79 unmodified lines2870 2871 return rv2872 2873 def consume_value(2872- self, ctx: Context, opts: t.Mapping[str, "Parameter"]2874+ self, ctx: Context, opts: t.Mapping[str, Parameter]2875 ) -> t.Tuple[t.Any, ParameterSource]:2876 value, source = super().consume_value(ctx, opts)2877 2878 # The parser will emit a sentinel value if the option can be130 unmodified linesmodified:src/click/decorators.py+12 added-10 removed
1+from __future__ import annotations2+3 import inspect4 import typing as t5 from functools import update_wrapper6 from gettext import gettext as _17 unmodified lines24 _AnyCallable = t.Callable[..., t.Any]25 FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])26 27 26-def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]":28+def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]:29 """Marks a callback as wanting to receive the current context30 object as first argument.31 """32 31- def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":33+ def new_func(*args: P.args, **kwargs: P.kwargs) -> R:34 return f(get_current_context(), *args, **kwargs)35 36 return update_wrapper(new_func, f)37 38 37-def pass_obj(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":39+def pass_obj(f: t.Callable[te.Concatenate[t.Any, P], R]) -> t.Callable[P, R]:40 """Similar to :func:`pass_context`, but only pass the object on the41 context onwards (:attr:`Context.obj`). This is useful if that object42 represents the state of a nested system.43 """44 43- def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":45+ def new_func(*args: P.args, **kwargs: P.kwargs) -> R:46 return f(get_current_context().obj, *args, **kwargs)47 48 return update_wrapper(new_func, f)49 50 51 def make_pass_decorator(52 object_type: t.Type[T], ensure: bool = False51-) -> t.Callable[["t.Callable[te.Concatenate[T, P], R]"], "t.Callable[P, R]"]:53+) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]:54 """Given an object type this creates a decorator that will work55 similar to :func:`pass_obj` but instead of passing the object of the56 current context, it will find the innermost context of type57 :func:`object_type`.14 unmodified lines72 :param ensure: if set to `True`, a new object will be created and73 remembered on the context if it's not there yet.74 """75 74- def decorator(f: "t.Callable[te.Concatenate[T, P], R]") -> "t.Callable[P, R]":75- def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":76+ def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:77+ def new_func(*args: P.args, **kwargs: P.kwargs) -> R:78 ctx = get_current_context()79 80 obj: t.Optional[T]81 if ensure:16 unmodified lines98 99 100 def pass_meta_key(101 key: str, *, doc_description: t.Optional[str] = None100-) -> "t.Callable[[t.Callable[te.Concatenate[t.Any, P], R]], t.Callable[P, R]]":102+) -> t.Callable[[t.Callable[te.Concatenate[t.Any, P], R]], t.Callable[P, R]]:103 """Create a decorator that passes a key from104 :attr:`click.Context.meta` as the first argument to the decorated105 function.106 4 unmodified lines111 112 .. versionadded:: 8.0113 """114 113- def decorator(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":114- def new_func(*args: "P.args", **kwargs: "P.kwargs") -> R:115+ def decorator(f: t.Callable[te.Concatenate[t.Any, P], R]) -> t.Callable[P, R]:116+ def new_func(*args: P.args, **kwargs: P.kwargs) -> R:117 ctx = get_current_context()118 obj = ctx.meta[key]119 return ctx.invoke(f, obj, *args, **kwargs)120 435 unmodified linesmodified:src/click/exceptions.py+10 added-8 removed
1+from __future__ import annotations2+3 import typing as t4 from gettext import gettext as _5 from gettext import ngettext6 49 unmodified lines56 """57 58 exit_code = 259 58- def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None:60+ def __init__(self, message: str, ctx: t.Optional[Context] = None) -> None:61 super().__init__(message)62 self.ctx = ctx61- self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None63+ self.cmd: t.Optional[Command] = self.ctx.command if self.ctx else None64 65 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:66 if file is None:67 file = get_text_stderr()37 unmodified lines105 106 def __init__(107 self,108 message: str,107- ctx: t.Optional["Context"] = None,108- param: t.Optional["Parameter"] = None,109+ ctx: t.Optional[Context] = None,110+ param: t.Optional[Parameter] = None,111 param_hint: t.Optional[str] = None,112 ) -> None:113 super().__init__(message, ctx)114 self.param = param26 unmodified lines141 142 def __init__(143 self,144 message: t.Optional[str] = None,143- ctx: t.Optional["Context"] = None,144- param: t.Optional["Parameter"] = None,145+ ctx: t.Optional[Context] = None,146+ param: t.Optional[Parameter] = None,147 param_hint: t.Optional[str] = None,148 param_type: t.Optional[str] = None,149 ) -> None:150 super().__init__(message or "", ctx, param, param_hint)56 unmodified lines207 self,208 option_name: str,209 message: t.Optional[str] = None,210 possibilities: t.Optional[t.Sequence[str]] = None,209- ctx: t.Optional["Context"] = None,211+ ctx: t.Optional[Context] = None,212 ) -> None:213 if message is None:214 message = _("No such option: {name}").format(name=option_name)215 24 unmodified lines240 :param option_name: the name of the option being used incorrectly.241 """242 243 def __init__(242- self, option_name: str, message: str, ctx: t.Optional["Context"] = None244+ self, option_name: str, message: str, ctx: t.Optional[Context] = None245 ) -> None:246 super().__init__(message, ctx)247 self.option_name = option_name248 42 unmodified linesmodified:src/click/formatting.py+2 added
1+from __future__ import annotations2+3 import typing as t4 from contextlib import contextmanager5 from gettext import gettext as _6 297 unmodified linesmodified:src/click/globals.py+6 added-4 removed
1+from __future__ import annotations2+3 import typing as t4 from threading import local5 6 if t.TYPE_CHECKING:3 unmodified lines10 _local = local()11 12 13 @t.overload12-def get_current_context(silent: "te.Literal[False]" = False) -> "Context":14+def get_current_context(silent: te.Literal[False] = False) -> Context:15 ...16 17 18 @t.overload17-def get_current_context(silent: bool = ...) -> t.Optional["Context"]:19+def get_current_context(silent: bool = ...) -> t.Optional[Context]:20 ...21 22 21-def get_current_context(silent: bool = False) -> t.Optional["Context"]:23+def get_current_context(silent: bool = False) -> t.Optional[Context]:24 """Returns the current click context. This can be used as a way to25 access the current context object from anywhere. This is a more implicit26 alternative to the :func:`pass_context` decorator. This function is27 primarily useful for helpers such as :func:`echo` which might be15 unmodified lines43 44 return None45 46 45-def push_context(ctx: "Context") -> None:47+def push_context(ctx: Context) -> None:48 """Pushes a new context to the current stack."""49 _local.__dict__.setdefault("stack", []).append(ctx)50 51 19 unmodified linesmodified:src/click/parser.py+13 added-11 removed
19 unmodified lines20 # This code uses parts of optparse written by Gregory P. Ward and21 # maintained by the Python Software Foundation.22 # Copyright 2001-2006 Gregory P. Ward23 # Copyright 2002-2006 Python Software Foundation24+from __future__ import annotations25+26 import typing as t27 from collections import deque28 from gettext import gettext as _29 from gettext import ngettext34 unmodified lines64 nargs_spec = deque(nargs_spec)65 rv: t.List[t.Union[str, t.Tuple[t.Optional[str], ...], None]] = []66 spos: t.Optional[int] = None67 66- def _fetch(c: "te.Deque[V]") -> t.Optional[V]:68+ def _fetch(c: te.Deque[V]) -> t.Optional[V]:69 try:70 if spos is None:71 return c.popleft()72 else:43 unmodified lines116 return opt[:2], opt[2:]117 return first, opt[1:]118 119 118-def _normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str:120+def _normalize_opt(opt: str, ctx: t.Optional[Context]) -> str:121 if ctx is None or ctx.token_normalize_func is None:122 return opt123 prefix, opt = _split_opt(opt)124 return f"{prefix}{ctx.token_normalize_func(opt)}"1 unmodified line126 127 class _Option:128 def __init__(129 self,128- obj: "CoreOption",130+ obj: CoreOption,131 opts: t.Sequence[str],132 dest: t.Optional[str],133 action: t.Optional[str] = None,134 nargs: int = 1,26 unmodified lines161 @property162 def takes_value(self) -> bool:163 return self.action in ("store", "append")164 163- def process(self, value: t.Any, state: "_ParsingState") -> None:165+ def process(self, value: t.Any, state: _ParsingState) -> None:166 if self.action == "store":167 state.opts[self.dest] = value # type: ignore168 elif self.action == "store_const":169 state.opts[self.dest] = self.const # type: ignore8 unmodified lines178 state.order.append(self.obj)179 180 181 class _Argument:180- def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1):182+ def __init__(self, obj: CoreArgument, dest: t.Optional[str], nargs: int = 1):183 self.dest = dest184 self.nargs = nargs185 self.obj = obj186 187 def process(188 self,189 value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]],188- state: "_ParsingState",190+ state: _ParsingState,191 ) -> None:192 if self.nargs > 1:193 assert value is not None194 holes = sum(1 for x in value if x is None)19 unmodified lines214 def __init__(self, rargs: t.List[str]) -> None:215 self.opts: t.Dict[str, t.Any] = {}216 self.largs: t.List[str] = []217 self.rargs = rargs216- self.order: t.List["CoreParameter"] = []218+ self.order: t.List[CoreParameter] = []219 220 221 class _OptionParser:222 """The option parser is an internal class that is ultimately used to11 unmodified lines234 .. deprecated:: 8.2235 Will be removed in Click 9.0.236 """237 236- def __init__(self, ctx: t.Optional["Context"] = None) -> None:238+ def __init__(self, ctx: t.Optional[Context] = None) -> None:239 #: The :class:`~click.Context` for this parser. This might be240 #: `None` for some advanced use cases.241 self.ctx = ctx242 #: This controls how the parser deals with interspersed arguments.17 unmodified lines260 self._args: t.List[_Argument] = []261 262 def add_option(263 self,262- obj: "CoreOption",264+ obj: CoreOption,265 opts: t.Sequence[str],266 dest: t.Optional[str],267 action: t.Optional[str] = None,268 nargs: int = 1,15 unmodified lines284 for opt in option._long_opts:285 self._long_opt[opt] = option286 287 def add_argument(286- self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1288+ self, obj: CoreArgument, dest: t.Optional[str], nargs: int = 1289 ) -> None:290 """Adds a positional argument named `dest` to the parser.291 292 The `obj` can be used to identify the option in the order list2 unmodified lines295 self._args.append(_Argument(obj, dest=dest, nargs=nargs))296 297 def parse_args(298 self, args: t.List[str]297- ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]:299+ ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List[CoreParameter]]:300 """Parses positional arguments and returns ``(values, args, order)``301 for the parsed options and arguments as well as the leftover302 arguments if there are any. The order is a list of objects as they303 appear on the command line. If arguments appear multiple times they228 unmodified linesmodified:src/click/shell_completion.py+2 added
1+from __future__ import annotations2+3 import os4 import re5 import typing as t6 from gettext import gettext as _628 unmodified linesmodified:src/click/termui.py+3 added-1 removed
1+from __future__ import annotations2+3 import inspect4 import io5 import itertools6 import sys290 unmodified lines297 width: int = 36,298 file: t.Optional[t.TextIO] = None,299 color: t.Optional[bool] = None,300 update_min_steps: int = 1,299-) -> "ProgressBar[V]":301+) -> ProgressBar[V]:302 """This function creates an iterable context manager that can be used303 to iterate over something while showing a progress bar. It will304 either iterate over the `iterable` or `length` items (that are counted305 up). While iteration happens, this function will print a rendered481 unmodified linesmodified:src/click/testing.py+6 added-4 removed
1+from __future__ import annotations2+3 import contextlib4 import io5 import os6 import shlex97 unmodified lines104 """Holds the captured result of an invoked CLI script."""105 106 def __init__(107 self,106- runner: "CliRunner",108+ runner: CliRunner,109 stdout_bytes: bytes,110 stderr_bytes: t.Optional[bytes],111 return_value: t.Any,112 exit_code: int,75 unmodified lines188 self.env: t.Mapping[str, t.Optional[str]] = env or {}189 self.echo_stdin = echo_stdin190 self.mix_stderr = mix_stderr191 190- def get_default_prog_name(self, cli: "Command") -> str:192+ def get_default_prog_name(self, cli: Command) -> str:193 """Given a command object it will return the default program name194 for it. The default is the `name` attribute or ``"root"`` if not195 set.196 """152 unmodified lines349 formatting.FORCED_WIDTH = old_forced_width350 351 def invoke(352 self,351- cli: "Command",353+ cli: Command,354 args: t.Optional[t.Union[str, t.Sequence[str]]] = None,355 input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,356 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,357 catch_exceptions: bool = True,92 unmodified lines450 )451 452 @contextlib.contextmanager453 def isolated_filesystem(452- self, temp_dir: t.Optional[t.Union[str, "os.PathLike[str]"]] = None454+ self, temp_dir: t.Optional[t.Union[str, os.PathLike[str]]] = None455 ) -> t.Iterator[str]:456 """A context manager that creates a temporary directory and457 changes the current working directory to it. This isolates tests458 that affect the contents of the CWD to prevent them from23 unmodified linesmodified:src/click/types.py+45 added-43 removed
1+from __future__ import annotations2+3 import os4 import stat5 import sys6 import typing as t70 unmodified lines77 78 def __call__(79 self,80 value: t.Any,79- param: t.Optional["Parameter"] = None,80- ctx: t.Optional["Context"] = None,81+ param: t.Optional[Parameter] = None,82+ ctx: t.Optional[Context] = None,83 ) -> t.Any:84 if value is not None:85 return self.convert(value, param, ctx)86 85- def get_metavar(self, param: "Parameter") -> t.Optional[str]:87+ def get_metavar(self, param: Parameter) -> t.Optional[str]:88 """Returns the metavar default for this param if it provides one."""89 88- def get_missing_message(self, param: "Parameter") -> t.Optional[str]:90+ def get_missing_message(self, param: Parameter) -> t.Optional[str]:91 """Optionally might return extra information about a missing92 parameter.93 94 .. versionadded:: 2.095 """96 97 def convert(96- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]98+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]99 ) -> t.Any:100 """Convert the value to the correct type. This is not called if101 the value is ``None`` (the missing value).102 27 unmodified lines130 131 def fail(132 self,133 message: str,132- param: t.Optional["Parameter"] = None,133- ctx: t.Optional["Context"] = None,134- ) -> "t.NoReturn":134+ param: t.Optional[Parameter] = None,135+ ctx: t.Optional[Context] = None,136+ ) -> t.NoReturn:137 """Helper method to fail with an invalid value message."""138 raise BadParameter(message, ctx=ctx, param=param)139 140 def shell_complete(139- self, ctx: "Context", param: "Parameter", incomplete: str140- ) -> t.List["CompletionItem"]:141+ self, ctx: Context, param: Parameter, incomplete: str142+ ) -> t.List[CompletionItem]:143 """Return a list of144 :class:`~click.shell_completion.CompletionItem` objects for the145 incomplete value. Most types do not provide completions, but146 some do, and this allows custom types to provide custom26 unmodified lines173 info_dict["func"] = self.func174 return info_dict175 176 def convert(175- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]177+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]178 ) -> t.Any:179 try:180 return self.func(value)181 except ValueError:8 unmodified lines190 class UnprocessedParamType(ParamType):191 name = "text"192 193 def convert(192- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]194+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]195 ) -> t.Any:196 return value197 198 def __repr__(self) -> str:3 unmodified lines202 class StringParamType(ParamType):203 name = "text"204 205 def convert(204- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]206+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]207 ) -> t.Any:208 if isinstance(value, bytes):209 enc = _get_argv_encoding()210 try:42 unmodified lines253 info_dict["choices"] = self.choices254 info_dict["case_sensitive"] = self.case_sensitive255 return info_dict256 255- def get_metavar(self, param: "Parameter") -> str:257+ def get_metavar(self, param: Parameter) -> str:258 choices_str = "|".join(self.choices)259 260 # Use curly braces to indicate a required argument.261 if param.required and param.param_type_name == "argument":1 unmodified line263 264 # Use square braces to indicate an option or optional argument.265 return f"[{choices_str}]"266 265- def get_missing_message(self, param: "Parameter") -> str:267+ def get_missing_message(self, param: Parameter) -> str:268 return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))269 270 def convert(269- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]271+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]272 ) -> t.Any:273 # Match through normalization and case sensitivity274 # first do token_normalize_func, then lowercase275 # preserve original `value` to produce an accurate message in32 unmodified lines308 def __repr__(self) -> str:309 return f"Choice({list(self.choices)})"310 311 def shell_complete(310- self, ctx: "Context", param: "Parameter", incomplete: str311- ) -> t.List["CompletionItem"]:312+ self, ctx: Context, param: Parameter, incomplete: str313+ ) -> t.List[CompletionItem]:314 """Complete choices that start with the incomplete value.315 316 :param ctx: Invocation context for this command.317 :param param: The parameter that is requesting completion.48 unmodified lines366 info_dict = super().to_info_dict()367 info_dict["formats"] = self.formats368 return info_dict369 368- def get_metavar(self, param: "Parameter") -> str:370+ def get_metavar(self, param: Parameter) -> str:371 return f"[{'|'.join(self.formats)}]"372 373 def _try_to_convert_date(self, value: t.Any, format: str) -> t.Optional[datetime]:374 try:1 unmodified line376 except ValueError:377 return None378 379 def convert(378- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]380+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]381 ) -> t.Any:382 if isinstance(value, datetime):383 return value384 21 unmodified lines406 class _NumberParamTypeBase(ParamType):407 _number_class: t.ClassVar[t.Type[t.Any]]408 409 def convert(408- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]410+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]411 ) -> t.Any:412 try:413 return self._number_class(value)414 except ValueError:32 unmodified lines447 )448 return info_dict449 450 def convert(449- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]451+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]452 ) -> t.Any:453 import operator454 455 rv = super().convert(value, param, ctx)21 unmodified lines477 )478 479 return rv480 479- def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:481+ def _clamp(self, bound: float, dir: te.Literal[1, -1], open: bool) -> float:482 """Find the valid value to clamp to bound in the given483 direction.484 485 :param bound: The boundary value.46 unmodified lines532 533 name = "integer range"534 535 def _clamp( # type: ignore534- self, bound: int, dir: "te.Literal[1, -1]", open: bool536+ self, bound: int, dir: te.Literal[1, -1], open: bool537 ) -> int:538 if not open:539 return bound540 40 unmodified lines581 582 if (min_open or max_open) and clamp:583 raise TypeError("Clamping is not supported for open bounds.")584 583- def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:585+ def _clamp(self, bound: float, dir: te.Literal[1, -1], open: bool) -> float:586 if not open:587 return bound588 589 # Could use Python 3.9's math.nextafter here, but clamping an5 unmodified lines595 class BoolParamType(ParamType):596 name = "boolean"597 598 def convert(597- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]599+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]600 ) -> t.Any:601 if value in {False, True}:602 return bool(value)603 16 unmodified lines620 class UUIDParameterType(ParamType):621 name = "uuid"622 623 def convert(622- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]624+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]625 ) -> t.Any:626 import uuid627 628 if isinstance(value, uuid.UUID):60 unmodified lines689 info_dict = super().to_info_dict()690 info_dict.update(mode=self.mode, encoding=self.encoding)691 return info_dict692 691- def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool:693+ def resolve_lazy_flag(self, value: t.Union[str, os.PathLike[str]]) -> bool:694 if self.lazy is not None:695 return self.lazy696 if os.fspath(value) == "-":697 return False2 unmodified lines700 return False701 702 def convert(703 self,702- value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]],703- param: t.Optional["Parameter"],704- ctx: t.Optional["Context"],704+ value: t.Union[str, os.PathLike[str], t.IO[t.Any]],705+ param: t.Optional[Parameter],706+ ctx: t.Optional[Context],707 ) -> t.IO[t.Any]:708 if _is_file_like(value):709 return value710 31 unmodified lines742 except OSError as e: # noqa: B014743 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)744 745 def shell_complete(744- self, ctx: "Context", param: "Parameter", incomplete: str745- ) -> t.List["CompletionItem"]:746+ self, ctx: Context, param: Parameter, incomplete: str747+ ) -> t.List[CompletionItem]:748 """Return a special completion marker that tells the completion749 system to use the shell to provide file path completions.750 751 :param ctx: Invocation context for this command.6 unmodified lines758 759 return [CompletionItem(incomplete, type="file")]760 761 760-def _is_file_like(value: t.Any) -> "te.TypeGuard[t.IO[t.Any]]":762+def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:763 return hasattr(value, "read") or hasattr(value, "write")764 765 766 class Path(ParamType):72 unmodified lines839 )840 return info_dict841 842 def coerce_path_result(841- self, value: "t.Union[str, os.PathLike[str]]"842- ) -> "t.Union[str, bytes, os.PathLike[str]]":843+ self, value: t.Union[str, os.PathLike[str]]844+ ) -> t.Union[str, bytes, os.PathLike[str]]:845 if self.type is not None and not isinstance(value, self.type):846 if self.type is str:847 return os.fsdecode(value)848 elif self.type is bytes:4 unmodified lines853 return value854 855 def convert(856 self,855- value: "t.Union[str, os.PathLike[str]]",856- param: t.Optional["Parameter"],857- ctx: t.Optional["Context"],858- ) -> "t.Union[str, bytes, os.PathLike[str]]":857+ value: t.Union[str, os.PathLike[str]],858+ param: t.Optional[Parameter],859+ ctx: t.Optional[Context],860+ ) -> t.Union[str, bytes, os.PathLike[str]]:861 rv = value862 863 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")864 60 unmodified lines925 926 return self.coerce_path_result(rv)927 928 def shell_complete(927- self, ctx: "Context", param: "Parameter", incomplete: str928- ) -> t.List["CompletionItem"]:929+ self, ctx: Context, param: Parameter, incomplete: str930+ ) -> t.List[CompletionItem]:931 """Return a special completion marker that tells the completion932 system to use the shell to provide path completions for only933 directories or any paths.934 39 unmodified lines974 def arity(self) -> int: # type: ignore975 return len(self.types)976 977 def convert(976- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]978+ self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]979 ) -> t.Any:980 len_type = len(self.types)981 len_value = len(value)982 105 unmodified linesmodified:src/click/utils.py+10 added-8 removed
1+from __future__ import annotations2+3 import os4 import re5 import sys6 import typing as t24 unmodified lines31 def _posixify(name: str) -> str:32 return "-".join(name.split()).lower()33 34 33-def safecall(func: "t.Callable[P, R]") -> "t.Callable[P, t.Optional[R]]":35+def safecall(func: t.Callable[P, R]) -> t.Callable[P, t.Optional[R]]:36 """Wraps a function so that it swallows exceptions."""37 36- def wrapper(*args: "P.args", **kwargs: "P.kwargs") -> t.Optional[R]:38+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> t.Optional[R]:39 try:40 return func(*args, **kwargs)41 except Exception:42 pass70 unmodified lines113 """114 115 def __init__(116 self,115- filename: t.Union[str, "os.PathLike[str]"],117+ filename: t.Union[str, os.PathLike[str]],118 mode: str = "r",119 encoding: t.Optional[str] = None,120 errors: t.Optional[str] = "strict",121 atomic: bool = False,54 unmodified lines176 """177 if self.should_close:178 self.close()179 178- def __enter__(self) -> "LazyFile":180+ def __enter__(self) -> LazyFile:181 return self182 183 def __exit__(184 self,14 unmodified lines199 200 def __getattr__(self, name: str) -> t.Any:201 return getattr(self._file, name)202 201- def __enter__(self) -> "KeepOpenFile":203+ def __enter__(self) -> KeepOpenFile:204 return self205 206 def __exit__(207 self,112 unmodified lines320 file.write(out) # type: ignore321 file.flush()322 323 322-def get_binary_stream(name: "te.Literal['stdin', 'stdout', 'stderr']") -> t.BinaryIO:324+def get_binary_stream(name: te.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:325 """Returns a system stream for byte processing.326 327 :param name: the name of the stream to open. Valid names are ``'stdin'``,328 ``'stdout'`` and ``'stderr'``4 unmodified lines333 return opener()334 335 336 def get_text_stream(335- name: "te.Literal['stdin', 'stdout', 'stderr']",337+ name: te.Literal["stdin", "stdout", "stderr"],338 encoding: t.Optional[str] = None,339 errors: t.Optional[str] = "strict",340 ) -> t.TextIO:341 """Returns a system stream for text processing. This usually returns61 unmodified lines403 return f404 405 406 def format_filename(405- filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]",407+ filename: t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]],408 shorten: bool = False,409 ) -> str:410 """Format a filename as a string for display. Ensures the filename can be411 displayed by replacing any invalid bytes or surrogate escapes in the name215 unmodified linesmodified:tests/test_imports.py+1 added
25 unmodified lines26 click.echo(json.dumps(rv))27 """28 29 ALLOWED_IMPORTS = {30+ "__future__",31 "weakref",32 "os",33 "struct",34 "collections",35 unmodified linesmodified:CHANGES.rst+3 added
22 unmodified lines23 - ``Parameter.add_to_parser`` (on both ``Argument`` and ``Option``) is24 unneeded. Parsing works directly without building a separate parser.25 - ``split_arg_string`` is moved from ``parser`` to ``shell_completion``.26 27+- Enable deferred evaluation of annotations with28+ ``from __future__ import annotations``. :pr:`2270`29 30+31 Version 8.1.732 -------------33 34 Released 2023-08-171100 unmodified lines