`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
Provenance
- Commit
ddede21- Tree
6d464eb- Author
Andreas Backx <AndreasBackx@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
d2e4a42
4 files changed+46 added−44 removed
modified:src/click/core.py+35 added-40 removed
5 unmodified lines6 import inspect7 import os8 import sys9 import typing as t10+from abc import ABC11+from abc import abstractmethod12 from collections import abc13 from collections import Counter14 from contextlib import AbstractContextManager15 from contextlib import contextmanager823 unmodified lines839 # 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)844 845 # Track all kwargs as params, so that forward() will pass846 # them on in subsequent calls.847 ctx.params.update(kwargs)471 unmodified lines1319 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 continue724 unmodified lines2052 2053 return iter(value)2054 2055 2056-class Parameter:2056+class 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 lines2174 ]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_value64 unmodified lines2247 2248 def __repr__(self) -> str:2249 return f"<{self.__class__.__name__} {self.name}>"2250 2251+ @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]]: ...2255 2256 @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.name2262 2263 def make_metavar(self, ctx: Context) -> str:2264 if self.metavar is not None:2265 return self.metavar40 unmodified lines2306 2307 .. 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)2311 2313- 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.default2314 2315 if call and callable(value):2316 value = value()2317 2318 return value2319 2321- 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: ...2322 2323 def consume_value(2324 self, ctx: Context, opts: cabc.Mapping[str, t.Any]2325 ) -> tuple[t.Any, ParameterSource]:7 unmodified lines2333 2334 :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.COMMANDLINE7 unmodified lines2349 value = envvar_value2350 source = ParameterSource.ENVIRONMENT2351 2352 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 lines2585 """2586 with augment_usage_errors(ctx, param=self):2587 value, source = self.consume_value(ctx, opts)2588 2590- ctx.set_parameter_source(self.name, source) # type: ignore2589+ ctx.set_parameter_source(self.name, source)2590 2591 # Display a deprecation warning if necessary.2592 if (2593 self.deprecated31 unmodified lines2625 # 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] = value2630 2631 return value, args2632 2633 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2640- pass2634+ return None2635 2636 def get_usage_pieces(self, ctx: Context) -> list[str]:2637 return []2638 2645- 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.2642+2643+ .. 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 lines2772 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs2773 )2774 2775 if prompt is True:2779- if self.name is None:2776+ if not self.name:2777 raise TypeError("'name' is required with 'prompt=True'.")2778 2779 prompt_text: str | None = self.name.replace("_", " ").capitalize()2780 elif prompt is False:185 unmodified lines2966 value = value()2967 2968 return value2969 2973- 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 result2975 2976 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 lines3013 name = None3014 3015 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 lines3121 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()}"3128 3129 if envvar is not None:130 unmodified lines3260 3261 if rv is not None:3262 return rv3263 3267- 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)3267 3268 if rv:156 unmodified lines3425 @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()3430 3431 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 lines3443 return var3444 3445 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 lines3461 3462 def get_usage_pieces(self, ctx: Context) -> list[str]:3463 return [self.make_metavar(ctx)]3464 3472- 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}'"3469 3470 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 linesmodified:src/click/exceptions.py+2 added-2 removed
127 unmodified lines128 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)135 136 return _("Invalid value for {param_hint}: {message}").format(27 unmodified lines164 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 = None171 172 param_hint = _join_param_hints(param_hint)140 unmodified linesmodified:src/click/shell_completion.py-2 removed
509 unmodified lines510 """511 if not isinstance(param, Argument):512 return False513 514- 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.COMMANDLINE148 unmodified linesmodified:CHANGES.rst+9 added
15 unmodified lines16 :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`21+22+ - :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 types1376 unmodified lines