Skip to content
Myr

`Parameter` typing improvements (#2805)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Andreas Backx · committed by GitHub · parent d2e4a42 · Browse files · 4 files+46 added−44 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Kevin Deldycke <kevin@deldycke.com>

Diff stats

4 files+46 added−44 removed

  • other:+46 added−44 removed

4 files+46 added−44 removed

modified:src/click/core.py+35 added-40 removed
5 unmodified lines
6import inspect7import os8import sys9import typing as t10from abc import ABC11from abc import abstractmethod12from collections import abc13from collections import Counter14from contextlib import AbstractContextManager15from contextlib import contextmanager
823 unmodified lines
839 # https://github.com/pallets/click/issues/3065840 # https://github.com/pallets/click/pull/3068841 if default_value is UNSET:842 default_value = None841 kwargs[param.name] = param.type_cast_value( # type: ignore842 ctx, default_value843 )843 kwargs[param.name] = param.type_cast_value(ctx, default_value)844845 # Track all kwargs as params, so that forward() will pass846 # them on in subsequent calls.847 ctx.params.update(kwargs)
471 unmodified lines
1319 not isinstance(param, Option)1320 or param.hidden1321 or (1322 not param.multiple1323 and ctx.get_parameter_source(param.name) # type: ignore1323 and ctx.get_parameter_source(param.name)1324 is ParameterSource.COMMANDLINE1325 )1326 ):1327 continue
724 unmodified lines
20522053 return iter(value)205420552056class Parameter:2056class Parameter(ABC):2057 r"""A parameter to a command comes in two versions: they are either2058 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently2059 not supported by design as some of the internals for parsing are2060 intentionally not finalized.
113 unmodified lines
2174 ]2175 | None = None,2176 deprecated: bool | str = False,2177 ) -> None:2178 self.name: str | None2178 self.name: str2179 self.opts: list[str]2180 self.secondary_opts: list[str]2181 self.name, self.opts, self.secondary_opts = self._parse_decls(2182 param_decls or (), expose_value
64 unmodified lines
22472248 def __repr__(self) -> str:2249 return f"<{self.__class__.__name__} {self.name}>"22502251 @abstractmethod2252 def _parse_decls(2253 self, decls: cabc.Sequence[str], expose_value: bool2253 ) -> tuple[str | None, list[str], list[str]]:2254 raise NotImplementedError()2254 ) -> tuple[str, list[str], list[str]]: ...22552256 @property2257 def human_readable_name(self) -> str:2258 """Returns the human readable name of this parameter. This is the2259 same as the name for options, but the metavar for arguments.2260 """2261 return self.name # type: ignore2261 return self.name22622263 def make_metavar(self, ctx: Context) -> str:2264 if self.metavar is not None:2265 return self.metavar
40 unmodified lines
23062307 .. versionchanged:: 8.02308 Added the ``call`` parameter.2309 """2310 name = self.name2311 value = ctx.lookup_default(name, call=False) if name is not None else None2310 value = ctx.lookup_default(self.name, call=False)23112313 if value is None and not ctx._default_map_has(name):2312 if value is None and not ctx._default_map_has(self.name):2313 value = self.default23142315 if call and callable(value):2316 value = value()23172318 return value23192321 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:2322 raise NotImplementedError()2320 @abstractmethod2321 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: ...23222323 def consume_value(2324 self, ctx: Context, opts: cabc.Mapping[str, t.Any]2325 ) -> tuple[t.Any, ParameterSource]:
7 unmodified lines
23332334 :meta private:2335 """2336 # Collect from the parse the value passed by the user to the CLI.2338 value = opts.get(self.name, UNSET) # type: ignore2337 value = opts.get(self.name, UNSET)2338 # If the value is set, it means it was sourced from the command line by the2339 # parser, otherwise it left unset by default.2340 source = (2341 ParameterSource.COMMANDLINE
7 unmodified lines
2349 value = envvar_value2350 source = ParameterSource.ENVIRONMENT23512352 if value is UNSET:2354 default_map_value = ctx.lookup_default(self.name) # type: ignore[arg-type]2353 default_map_value = ctx.lookup_default(self.name)2354 if default_map_value is not None or ctx._default_map_has(self.name):2355 value = default_map_value2356 source = ParameterSource.DEFAULT_MAP2357
227 unmodified lines
2585 """2586 with augment_usage_errors(ctx, param=self):2587 value, source = self.consume_value(ctx, opts)25882590 ctx.set_parameter_source(self.name, source) # type: ignore2589 ctx.set_parameter_source(self.name, source)25902591 # Display a deprecation warning if necessary.2592 if (2593 self.deprecated
31 unmodified lines
2625 # targeting the same variable name. This prevents parameters competing for2626 # the same name to override each other.2627 and (self.name not in ctx.params or ctx.params[self.name] is UNSET)2628 ):2630 # Click is logically enforcing that the name is None if the parameter is2631 # not to be exposed. We still assert it here to please the type checker.2632 assert self.name is not None, (2633 f"{self!r} parameter's name should not be None when exposing value."2634 )2629 ctx.params[self.name] = value26302631 return value, args26322633 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2640 pass2634 return None26352636 def get_usage_pieces(self, ctx: Context) -> list[str]:2637 return []26382645 def get_error_hint(self, ctx: Context) -> str:2639 def get_error_hint(self, ctx: Context | None) -> str:2640 """Get a stringified version of the param for use in error messages to2641 indicate which param caused the error.26422643 .. versionchanged:: 8.4.02644 ``ctx`` can be ``None``.2645 """2646 hint_list = self.opts or [self.human_readable_name]2647 return " / ".join(f"'{x}'" for x in hint_list)2648
123 unmodified lines
2772 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs2773 )27742775 if prompt is True:2779 if self.name is None:2776 if not self.name:2777 raise TypeError("'name' is required with 'prompt=True'.")27782779 prompt_text: str | None = self.name.replace("_", " ").capitalize()2780 elif prompt is False:
185 unmodified lines
2966 value = value()29672968 return value29692973 def get_error_hint(self, ctx: Context) -> str:2970 def get_error_hint(self, ctx: Context | None) -> str:2971 result = super().get_error_hint(ctx)2972 if self.show_envvar and self.envvar is not None:2973 result += f" (env var: '{self.envvar}')"2974 return result29752976 def _parse_decls(2977 self, decls: cabc.Sequence[str], expose_value: bool2981 ) -> tuple[str | None, list[str], list[str]]:2978 ) -> tuple[str, list[str], list[str]]:2979 opts = []2980 secondary_opts = []2981 name = None2982 possible_names = []
30 unmodified lines
3013 name = None30143015 if name is None:3016 if not expose_value:3020 return None, opts, secondary_opts3017 return "", opts, secondary_opts3018 raise TypeError(3019 f"Could not determine name for option with declarations {decls!r}"3020 )3021
99 unmodified lines
3121 if envvar is None:3122 if (3123 self.allow_from_autoenv3124 and ctx.auto_envvar_prefix is not None3128 and self.name is not None3125 and self.name3126 ):3127 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"31283129 if envvar is not None:
130 unmodified lines
32603261 if rv is not None:3262 return rv32633267 if (3268 self.allow_from_autoenv3269 and ctx.auto_envvar_prefix is not None3270 and self.name is not None3271 ):3264 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name:3265 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"3266 rv = os.environ.get(envvar)32673268 if rv:
156 unmodified lines
3425 @property3426 def human_readable_name(self) -> str:3427 if self.metavar is not None:3428 return self.metavar3436 return self.name.upper() # type: ignore3429 return self.name.upper()34303431 def make_metavar(self, ctx: Context) -> str:3432 if self.metavar is not None:3433 return self.metavar3434 var = self.type.get_metavar(param=self, ctx=ctx)3435 if not var:3443 var = self.name.upper() # type: ignore3436 var = self.name.upper()3437 if self.deprecated:3438 var += "!"3439 if not self.required:3440 var = f"[{var}]"
2 unmodified lines
3443 return var34443445 def _parse_decls(3446 self, decls: cabc.Sequence[str], expose_value: bool3454 ) -> tuple[str | None, list[str], list[str]]:3447 ) -> tuple[str, list[str], list[str]]:3448 if not decls:3449 if not expose_value:3457 return None, [], []3450 return "", [], []3451 raise TypeError("Argument is marked as exposed, but does not have a name.")3452 if len(decls) == 1:3453 name = arg = decls[0]3454 name = name.replace("-", "_").lower()
6 unmodified lines
34613462 def get_usage_pieces(self, ctx: Context) -> list[str]:3463 return [self.make_metavar(ctx)]34643472 def get_error_hint(self, ctx: Context) -> str:3473 return f"'{self.make_metavar(ctx)}'"3465 def get_error_hint(self, ctx: Context | None) -> str:3466 if ctx is not None:3467 return f"'{self.make_metavar(ctx)}'"3468 return f"'{self.human_readable_name}'"34693470 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:3471 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)3472
23 unmodified lines
modified:src/click/exceptions.py+2 added-2 removed
127 unmodified lines
128 def format_message(self) -> str:129 if self.param_hint is not None:130 param_hint = self.param_hint131 elif self.param is not None:132 param_hint = self.param.get_error_hint(self.ctx) # type: ignore132 param_hint = self.param.get_error_hint(self.ctx)133 else:134 return _("Invalid value: {message}").format(message=self.message)135136 return _("Invalid value for {param_hint}: {message}").format(
27 unmodified lines
164 def format_message(self) -> str:165 if self.param_hint is not None:166 param_hint: cabc.Sequence[str] | str | None = self.param_hint167 elif self.param is not None:168 param_hint = self.param.get_error_hint(self.ctx) # type: ignore168 param_hint = self.param.get_error_hint(self.ctx)169 else:170 param_hint = None171172 param_hint = _join_param_hints(param_hint)
140 unmodified lines
modified:src/click/shell_completion.py-2 removed
509 unmodified lines
510 """511 if not isinstance(param, Argument):512 return False513514 assert param.name is not None515 # Will be None if expose_value is False.514 value = ctx.params.get(param.name)515 return (516 param.nargs == -1517 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE
148 unmodified lines
modified:CHANGES.rst+9 added
15 unmodified lines
16 :class:`~typing.TypedDict` subclasses instead of17 ``dict[str, Any]``.18 - :class:`CompositeParamType` and the number-range base are now19 generic with abstract methods.20- :class:`Parameter` typing improvements. :pr:`2805`2122 - :class:`Parameter` is now an abstract base class, making explicit23 that it cannot be instantiated directly.24 - :attr:`Parameter.name` is now ``str`` instead of ``str | None``.25 When ``expose_value=False``, the name is set to ``""`` instead26 of ``None``.27 - The ``ctx`` parameter of :meth:`Parameter.get_error_hint` is now28 typed as ``Context | None``, matching the runtime behavior.29- Split string values from ``default_map`` for parameters with ``nargs > 1``30 or :class:`Tuple` type, matching environment variable behavior.31 :issue:`2745` :pr:`3364`32- Auto-detect ``type=UNPROCESSED`` for ``flag_value`` of non-basic types
1376 unmodified lines