Update examples in docs, adds version update admonitions
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 78a4efc · Browse files · 4 files·+25 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Refs: https://github.com/pallets/click/pull/3371#pullrequestreview-4173325028
Diff stats
4 files+25 added−6 removed
- other:+25 added−6 removed
Provenance
- Commit
ded5b69- Tree
7c0805c- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
78a4efc
4 files changed+25 added−6 removed
modified:docs/parameter-types.md+21 added-2 removed
68 unmodified lines697071727374757677787980818275 unmodified lines1581591601611621631641651661671681691701711721621731741751651761771781791804 unmodified lines18518618718818919019119219319419519619719819920020120220320420568 unmodified linesThe resulting value from an option will always be one of the originally passed choicesregardless of `case_sensitive`.```
```{versionchanged} 8.4.0{class}`Choice` is now generic. Parameterize it with the choice value type({class}`!Choice[HashType]` for an enum, {class}`!Choice[str]` for plainstrings) to enable type-checked consumers.```
(ranges)=
### Int and Float Ranges
75 unmodified linesTo implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Pythonfunction that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`method to convert the value from a string to the correct type.
{class}`ParamType` is generic in the converted value type: parameterize it withthe type returned by `convert` so that consumers (and type checkers) can relyon the narrowed return type.
The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, andconverts them into regular integers.
```pythonimport click
class BasedIntParamType(click.ParamType):class BasedIntParamType(click.ParamType[int]): name = "integer"
def convert(self, value, param, ctx): def convert(self, value, param, ctx) -> int: if isinstance(value, int): return value
try:4 unmodified lines return int(value, 10) except ValueError: self.fail(f"{value!r} is not a valid integer", param, ctx)
BASED_INT = BasedIntParamType()```
The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` ifconversion fails. The `param` and `ctx` arguments may be `None` in some cases such as prompts.
Values from user input or the command line will be strings, but default values and Python arguments may already be thecorrect type. The custom type should check at the top if the value is already valid and pass it through to support thosecases.
```{versionchanged} 8.4.0{class}`ParamType` is now a generic abstract base class. Parameterize it withthe converted value type ({class}`!ParamType[int]` for an integer-returningtype) so that {meth}`~ParamType.convert` and downstream consumers carry thenarrowed type.```modified:docs/shell-completion.md+1 added-1 removed
118 unmodified lines119 120 In this example, the type will suggest environment variables that start with the incomplete value.121 122 ```python123-class EnvVarType(ParamType):123+class EnvVarType(ParamType[str]):124 name = "envvar"125 126 def shell_complete(self, ctx, param, incomplete):127 return [122 unmodified linesmodified:docs/support-multiple-versions.md+1 added-1 removed
53 unmodified lines54 55 Here's an example ``ParamType`` subclass which uses this:56 57 ```python58-class CommaDelimitedString(click.ParamType):58+class CommaDelimitedString(click.ParamType[str]):59 @add_ctx_arg60 def get_metavar(self, param: click.Parameter, ctx: click.Context | None) -> str:61 return "TEXT,TEXT,..."62 ```modified:examples/validation/validation.py+2 added-2 removed
7 unmodified lines8 raise click.BadParameter("Should be a positive, even integer.")9 return value10 11 12-class URL(click.ParamType):12+class URL(click.ParamType[urlparse.ParseResult]):13 name = "url"14 15- def convert(self, value, param, ctx):15+ def convert(self, value, param, ctx) -> urlparse.ParseResult:16 if not isinstance(value, tuple):17 value = urlparse.urlparse(value)18 if value.scheme not in ("http", "https"):19 self.fail(29 unmodified lines