Add type annotations for instance attributes in `click.core` (#3463)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by GitHub · parents 9be25a2, d5da635 · Browse files · 1 file·+124 added−40 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+124 added−40 removed
- other:+124 added−40 removed
Provenance
- Commit
e34e526- Tree
410d647- Author
Kevin Deldycke <kdeldycke@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
9be25a2- Parent 2
d5da635
1 file changed+124 added−40 removed
modified:src/click/core.py+124 added-40 removed
46 unmodified lines47 from .utils import make_str48 from .utils import PacifyFlushWrapper49 50 if t.TYPE_CHECKING:51+ from typing_extensions import Self52+53 from .shell_completion import CompletionItem54 55 F = t.TypeVar("F", bound="t.Callable[..., t.Any]")56 V = t.TypeVar("V")61 unmodified lines118 119 @contextmanager120 def augment_usage_errors(121 ctx: Context, param: Parameter | None = None120-) -> cabc.Iterator[None]:122+) -> cabc.Generator[None]:123 """Context manager that attaches extra information to exceptions."""124 try:125 yield126 except BadParameter as e:177 unmodified lines304 #:305 #: .. versionadded:: 8.0306 formatter_class: type[HelpFormatter] = HelpFormatter307 308+ parent: Context | None309+ command: Command310+ info_name: str | None311+ params: dict[str, t.Any]312+ args: list[str]313+ _protected_args: list[str]314+ _opt_prefixes: set[str]315+ obj: t.Any316+ _meta: dict[str, t.Any]317+ default_map: cabc.MutableMapping[str, t.Any] | None318+ invoked_subcommand: str | None319+ terminal_width: int | None320+ max_content_width: int | None321+ allow_extra_args: bool322+ allow_interspersed_args: bool323+ ignore_unknown_options: bool324+ help_option_names: list[str]325+ token_normalize_func: t.Callable[[str], str] | None326+ resilient_parsing: bool327+ auto_envvar_prefix: str | None328+ color: bool | None329+ show_default: bool | None330+ _close_callbacks: list[t.Callable[[], t.Any]]331+ _depth: int332+ _parameter_source: dict[str, ParameterSource]333+ _param_default_explicit: dict[str, bool]334+ _exit_stack: ExitStack335+336 def __init__(337 self,338 command: Command,339 parent: Context | None = None,19 unmodified lines359 #: the descriptive information name360 self.info_name = info_name361 #: Map of parameter names to their parsed values. Parameters362 #: with ``expose_value=False`` are not stored.333- self.params: dict[str, t.Any] = {}363+ self.params = {}364 #: the leftover arguments.335- self.args: list[str] = []365+ self.args = []366 #: protected arguments. These are arguments that are prepended367 #: to `args` when certain parsing scenarios are encountered but368 #: must be never propagated to another arguments. This is used369 #: to implement nested parsing.340- self._protected_args: list[str] = []370+ self._protected_args = []371 #: the collected prefixes of the command's options.342- self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set()372+ self._opt_prefixes = set(parent._opt_prefixes) if parent else set()373 374 if obj is None and parent is not None:375 obj = parent.obj376 377 #: the user object stored.348- self.obj: t.Any = obj349- self._meta: dict[str, t.Any] = getattr(parent, "meta", {})378+ self.obj = obj379+ self._meta = getattr(parent, "meta", {})380 381 #: A dictionary (-like object) with defaults for parameters.382 if (383 default_map is None2 unmodified lines386 and parent.default_map is not None387 ):388 default_map = parent.default_map.get(info_name)389 360- self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map390+ self.default_map = default_map391 392 #: This flag indicates if a subcommand is going to be executed. A393 #: group callback can use this information to figure out if it's394 #: being executed directly or because the execution flow passes3 unmodified lines398 #: If chaining is enabled this will be set to ``'*'`` in case399 #: any commands are executed. It is however not possible to400 #: figure out which ones. If you require this knowledge you401 #: should use a :func:`result_callback`.372- self.invoked_subcommand: str | None = None402+ self.invoked_subcommand = None403 404 if terminal_width is None and parent is not None:405 terminal_width = parent.terminal_width406 407 #: The width of the terminal (None is autodetection).378- self.terminal_width: int | None = terminal_width408+ self.terminal_width = terminal_width409 410 if max_content_width is None and parent is not None:411 max_content_width = parent.max_content_width412 413 #: The maximum width of formatted content (None implies a sensible414 #: default which is 80 for most things).385- self.max_content_width: int | None = max_content_width415+ self.max_content_width = max_content_width416 417 if allow_extra_args is None:418 allow_extra_args = command.allow_extra_args419 9 unmodified lines429 #: Indicates if the context allows mixing of arguments and430 #: options or not.431 #:432 #: .. versionadded:: 3.0403- self.allow_interspersed_args: bool = allow_interspersed_args433+ self.allow_interspersed_args = allow_interspersed_args434 435 if ignore_unknown_options is None:436 ignore_unknown_options = command.ignore_unknown_options437 4 unmodified lines442 #: strongly discouraged because it's not possibly to losslessly443 #: forward all arguments.444 #:445 #: .. versionadded:: 4.0416- self.ignore_unknown_options: bool = ignore_unknown_options446+ self.ignore_unknown_options = ignore_unknown_options447 448 if help_option_names is None:449 if parent is not None:450 help_option_names = parent.help_option_names451 else:452 help_option_names = ["--help"]453 454 #: The names for the help options.425- self.help_option_names: list[str] = help_option_names455+ self.help_option_names = help_option_names456 457 if token_normalize_func is None and parent is not None:458 token_normalize_func = parent.token_normalize_func459 460 #: An optional normalization function for tokens. This is461 #: options, choices, commands etc.432- self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func462+ self.token_normalize_func = token_normalize_func463 464 #: Indicates if resilient parsing is enabled. In that case Click465 #: will do its best to not cause any failures and default values466 #: will be ignored. Useful for completion.437- self.resilient_parsing: bool = resilient_parsing467+ self.resilient_parsing = resilient_parsing468 469 # If there is no envvar prefix yet, but the parent has one and470 # the command on this level has a name, we can expand the envvar471 # prefix automatically.11 unmodified lines483 484 if auto_envvar_prefix is not None:485 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")486 457- self.auto_envvar_prefix: str | None = auto_envvar_prefix487+ self.auto_envvar_prefix = auto_envvar_prefix488 489 if color is None and parent is not None:490 color = parent.color491 492 #: Controls if styling output is wanted or not.463- self.color: bool | None = color493+ self.color = color494 495 if show_default is None and parent is not None:496 show_default = parent.show_default497 498 #: Show option default values when formatting help text.469- self.show_default: bool | None = show_default499+ self.show_default = show_default500 471- self._close_callbacks: list[t.Callable[[], t.Any]] = []501+ self._close_callbacks = []502 self._depth = 0473- self._parameter_source: dict[str, ParameterSource] = {}503+ self._parameter_source = {}504 # Tracks whether the option that currently owns each parameter slot in505 # :attr:`params` had its ``default`` set explicitly by the user. Used506 # to tie-break feature-switch groups where multiple options share a507 # parameter name and both fall back to their default value.508 # Refs: https://github.com/pallets/click/issues/3403479- self._param_default_explicit: dict[str, bool] = {}509+ self._param_default_explicit = {}510 self._exit_stack = ExitStack()511 512 @property513 def protected_args(self) -> list[str]:27 unmodified lines541 "ignore_unknown_options": self.ignore_unknown_options,542 "auto_envvar_prefix": self.auto_envvar_prefix,543 }544 515- def __enter__(self) -> Context:545+ def __enter__(self) -> Self:546 self._depth += 1547 push_context(self)548 return self549 11 unmodified lines561 562 return exit_result563 564 @contextmanager535- def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:565+ def scope(self, cleanup: bool = True) -> cabc.Generator[Context]:566 """This helper method can be used with the context object to promote567 it to the current thread local (see :func:`get_current_context`).568 The default behavior of this is to invoke the cleanup functions which569 can be disabled by setting `cleanup` to `False`. The cleanup444 unmodified lines1014 1015 #: the default for the :attr:`Context.ignore_unknown_options` flag.1016 ignore_unknown_options = False1017 1018+ name: str | None1019+ context_settings: cabc.MutableMapping[str, t.Any]1020+ callback: t.Callable[..., t.Any] | None1021+ params: list[Parameter]1022+ help: str | None1023+ epilog: str | None1024+ options_metavar: str | None1025+ short_help: str | None1026+ add_help_option: bool1027+ _help_option: Option | None1028+ no_args_is_help: bool1029+ hidden: bool1030+ deprecated: bool | str1031+1032 def __init__(1033 self,1034 name: str | None,1035 context_settings: cabc.MutableMapping[str, t.Any] | None = None,17 unmodified lines1053 if context_settings is None:1054 context_settings = {}1055 1056 #: an optional dictionary with defaults passed to the context.1013- self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings1057+ self.context_settings = context_settings1058 1059 #: the callback to execute when the command fires. This might be1060 #: `None` in which case nothing happens.1061 self.callback = callback1062 #: the list of parameters for this command in the order they1063 #: should show up in the help page and execute. Eager parameters1064 #: will automatically be handled before non eager ones.1021- self.params: list[Parameter] = params or []1065+ self.params = params or []1066 self.help = help1067 self.epilog = epilog1068 self.options_metavar = options_metavar1069 self.short_help = short_help566 unmodified lines1636 #: .. versionadded:: 8.01637 group_class: type[Group] | type[type] | None = None1638 # Literal[type] isn't valid, so use Type[type]1639 1640+ commands: cabc.MutableMapping[str, Command]1641+ invoke_without_command: bool1642+ subcommand_metavar: str1643+ chain: bool1644+ _result_callback: t.Callable[..., t.Any] | None1645+1646 def __init__(1647 self,1648 name: str | None = None,1649 commands: cabc.MutableMapping[str, Command]13 unmodified lines1663 elif isinstance(commands, abc.Sequence):1664 commands = {c.name: c for c in commands if c.name is not None}1665 1666 #: The registered subcommands by their exported names.1617- self.commands: cabc.MutableMapping[str, Command] = commands1667+ self.commands = commands1668 1669 if no_args_is_help is None:1670 no_args_is_help = not invoke_without_command1671 397 unmodified lines2069 This is a subclass of ``Group``. Commands are looked up first on this2070 group, then each of its sources.2071 """2072 2073+ sources: list[Group]2074+2075 def __init__(2076 self,2077 name: str | None = None,2078 sources: list[Group] | None = None,2079 **kwargs: t.Any,2080 ) -> None:2081 super().__init__(name, **kwargs)2082 #: The list of registered groups.2031- self.sources: list[Group] = sources or []2083+ self.sources = sources or []2084 2085 def add_source(self, group: Group) -> None:2086 """Add a group as a source of commands."""2087 self.sources.append(group)23 unmodified lines2111 2112 return sorted(rv)2113 2114 2063-def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2115+def _check_iter(value: cabc.Iterable[V]) -> cabc.Iterator[V]:2116 """Check if the value is iterable but not a string. Raises a type2117 error, or return an iterator over the value.2118 """2119 if isinstance(value, str):94 unmodified lines2214 """2215 2216 param_type_name = "parameter"2217 2218+ name: str2219+ opts: list[str]2220+ secondary_opts: list[str]2221+ # `Parameter.type` is annotated in `__init__` to avoid confusing mypy2222+ required: bool2223+ callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None2224+ nargs: int2225+ multiple: bool2226+ expose_value: bool2227+ default: t.Any | t.Callable[[], t.Any] | None2228+ _default_explicit: bool2229+ is_eager: bool2230+ metavar: str | None2231+ envvar: str | cabc.Sequence[str] | None2232+ _custom_shell_complete: (2233+ t.Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None2234+ )2235+ deprecated: bool | str2236+2237 def __init__(2238 self,2239 param_decls: cabc.Sequence[str] | None = None,2240 type: types.ParamType[t.Any] | t.Any | None = None,21 unmodified lines2262 ]2263 | None = None,2264 deprecated: bool | str = False,2265 ) -> None:2195- self.name: str2196- self.opts: list[str]2197- self.secondary_opts: list[str]2266 self.name, self.opts, self.secondary_opts = self._parse_decls(2267 param_decls or (), expose_value2268 )2269 self.type: types.ParamType[t.Any] = types.convert_type(type, default)10 unmodified lines2280 self.callback = callback2281 self.nargs = nargs2282 self.multiple = multiple2283 self.expose_value = expose_value2216- self.default: t.Any | t.Callable[[], t.Any] | None = default2284+ self.default = default2285 # Whether the user passed ``default`` explicitly to the constructor.2286 # Captured before any auto-derived default (like ``False`` for boolean2287 # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it2288 # remains ``False`` when the default was inferred rather than chosen.2289 # Refs: https://github.com/pallets/click/issues/34032222- self._default_explicit: bool = default is not UNSET2290+ self._default_explicit = default is not UNSET2291 self.is_eager = is_eager2292 self.metavar = metavar2293 self.envvar = envvar2294 self._custom_shell_complete = shell_complete566 unmodified lines2861 """2862 2863 param_type_name = "option"2864 2865+ prompt: str | None2866+ confirmation_prompt: bool | str2867+ prompt_required: bool2868+ hide_input: bool2869+ hidden: bool2870+2871+ _flag_needs_value: bool2872+ is_flag: bool2873+ is_bool_flag: bool2874+ flag_value: t.Any2875+2876+ count: bool2877+ allow_from_autoenv: bool2878+ help: str | None2879+ show_default: bool | str | None2880+ show_choices: bool2881+ show_envvar: bool2882+2883 def __init__(2884 self,2885 param_decls: cabc.Sequence[str] | None = None,2886 show_default: bool | str | None = None,24 unmodified lines2911 if prompt is True:2912 if not self.name:2913 raise TypeError("'name' is required with 'prompt=True'.")2914 2829- prompt_text: str | None = self.name.replace("_", " ").capitalize()2915+ prompt_text = self.name.replace("_", " ").capitalize()2916 elif prompt is False:2917 prompt_text = None2918 else:2919 prompt_text = prompt65 unmodified lines2985 self.type = types.UNPROCESSED2986 else:2987 self.type = guessed2988 2903- self.is_flag: bool = bool(is_flag)2904- self.is_bool_flag: bool = bool(2905- is_flag and isinstance(self.type, types.BoolParamType)2906- )2907- self.flag_value: t.Any = flag_value2989+ self.is_flag = bool(is_flag)2990+ self.is_bool_flag = self.is_flag and isinstance(self.type, types.BoolParamType)2991+ self.flag_value = flag_value2992 2993 # Set boolean flag default to False if unset and not required.2994 if self.is_bool_flag:2995 if self.default is UNSET and not self.required:639 unmodified lines