Add type annotations for instance attributes in `click.core`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by jorenham · committed by jorenham · parent 648d7c4 · 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
d5da635- Tree
25cb3ea- Author
jorenham <jhammudoglu@gmail.com>- Committer
jorenham <jhammudoglu@gmail.com>- Parent
648d7c4
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_help565 unmodified lines1635 #: .. versionadded:: 8.01636 group_class: type[Group] | type[type] | None = None1637 # Literal[type] isn't valid, so use Type[type]1638 1639+ commands: cabc.MutableMapping[str, Command]1640+ invoke_without_command: bool1641+ subcommand_metavar: str1642+ chain: bool1643+ _result_callback: t.Callable[..., t.Any] | None1644+1645 def __init__(1646 self,1647 name: str | None = None,1648 commands: cabc.MutableMapping[str, Command]13 unmodified lines1662 elif isinstance(commands, abc.Sequence):1663 commands = {c.name: c for c in commands if c.name is not None}1664 1665 #: The registered subcommands by their exported names.1616- self.commands: cabc.MutableMapping[str, Command] = commands1666+ self.commands = commands1667 1668 if no_args_is_help is None:1669 no_args_is_help = not invoke_without_command1670 390 unmodified lines2061 This is a subclass of ``Group``. Commands are looked up first on this2062 group, then each of its sources.2063 """2064 2065+ sources: list[Group]2066+2067 def __init__(2068 self,2069 name: str | None = None,2070 sources: list[Group] | None = None,2071 **kwargs: t.Any,2072 ) -> None:2073 super().__init__(name, **kwargs)2074 #: The list of registered groups.2023- self.sources: list[Group] = sources or []2075+ self.sources = sources or []2076 2077 def add_source(self, group: Group) -> None:2078 """Add a group as a source of commands."""2079 self.sources.append(group)23 unmodified lines2103 2104 return sorted(rv)2105 2106 2055-def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2107+def _check_iter(value: cabc.Iterable[V]) -> cabc.Iterator[V]:2108 """Check if the value is iterable but not a string. Raises a type2109 error, or return an iterator over the value.2110 """2111 if isinstance(value, str):94 unmodified lines2206 """2207 2208 param_type_name = "parameter"2209 2210+ name: str2211+ opts: list[str]2212+ secondary_opts: list[str]2213+ # `Parameter.type` is annotated in `__init__` to avoid confusing mypy2214+ required: bool2215+ callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None2216+ nargs: int2217+ multiple: bool2218+ expose_value: bool2219+ default: t.Any | t.Callable[[], t.Any] | None2220+ _default_explicit: bool2221+ is_eager: bool2222+ metavar: str | None2223+ envvar: str | cabc.Sequence[str] | None2224+ _custom_shell_complete: (2225+ t.Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None2226+ )2227+ deprecated: bool | str2228+2229 def __init__(2230 self,2231 param_decls: cabc.Sequence[str] | None = None,2232 type: types.ParamType[t.Any] | t.Any | None = None,21 unmodified lines2254 ]2255 | None = None,2256 deprecated: bool | str = False,2257 ) -> None:2187- self.name: str2188- self.opts: list[str]2189- self.secondary_opts: list[str]2258 self.name, self.opts, self.secondary_opts = self._parse_decls(2259 param_decls or (), expose_value2260 )2261 self.type: types.ParamType[t.Any] = types.convert_type(type, default)10 unmodified lines2272 self.callback = callback2273 self.nargs = nargs2274 self.multiple = multiple2275 self.expose_value = expose_value2208- self.default: t.Any | t.Callable[[], t.Any] | None = default2276+ self.default = default2277 # Whether the user passed ``default`` explicitly to the constructor.2278 # Captured before any auto-derived default (like ``False`` for boolean2279 # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it2280 # remains ``False`` when the default was inferred rather than chosen.2281 # Refs: https://github.com/pallets/click/issues/34032214- self._default_explicit: bool = default is not UNSET2282+ self._default_explicit = default is not UNSET2283 self.is_eager = is_eager2284 self.metavar = metavar2285 self.envvar = envvar2286 self._custom_shell_complete = shell_complete566 unmodified lines2853 """2854 2855 param_type_name = "option"2856 2857+ prompt: str | None2858+ confirmation_prompt: bool | str2859+ prompt_required: bool2860+ hide_input: bool2861+ hidden: bool2862+2863+ _flag_needs_value: bool2864+ is_flag: bool2865+ is_bool_flag: bool2866+ flag_value: t.Any2867+2868+ count: bool2869+ allow_from_autoenv: bool2870+ help: str | None2871+ show_default: bool | str | None2872+ show_choices: bool2873+ show_envvar: bool2874+2875 def __init__(2876 self,2877 param_decls: cabc.Sequence[str] | None = None,2878 show_default: bool | str | None = None,24 unmodified lines2903 if prompt is True:2904 if not self.name:2905 raise TypeError("'name' is required with 'prompt=True'.")2906 2821- prompt_text: str | None = self.name.replace("_", " ").capitalize()2907+ prompt_text = self.name.replace("_", " ").capitalize()2908 elif prompt is False:2909 prompt_text = None2910 else:2911 prompt_text = prompt65 unmodified lines2977 self.type = types.UNPROCESSED2978 else:2979 self.type = guessed2980 2895- self.is_flag: bool = bool(is_flag)2896- self.is_bool_flag: bool = bool(2897- is_flag and isinstance(self.type, types.BoolParamType)2898- )2899- self.flag_value: t.Any = flag_value2981+ self.is_flag = bool(is_flag)2982+ self.is_bool_flag = self.is_flag and isinstance(self.type, types.BoolParamType)2983+ self.flag_value = flag_value2984 2985 # Set boolean flag default to False if unset and not required.2986 if self.is_bool_flag:2987 if self.default is UNSET and not self.required:639 unmodified lines