Skip to content
Myr

support-multiple-versions.md

This file

Path

docs/support-multiple-versions.md

62 lines · 2.1 KiB · Markdown

Last changed by

`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489

History of this file

Take it

Add a doc for supporting 8.1.x|8.2.0 (#2929)David Lordbefore adoption2d610e3

lines 1–57why, one step back
1# Supporting Multiple Versions
23If you are a library maintainer, you may want to support multiple versions of4Click. See the Pallets [version policy] for information about our version5numbers and support policy.67[version policy]: https://palletsprojects.com/versions89Most features of Click are stable across releases, and don't require special10handling. However, feature releases may deprecate and change APIs. Occasionally,11a change will require special handling.1213## Use Feature Detection1415Prefer using feature detection. Looking at the version can be tempting, but is16often more brittle or results in more complicated code. Try to use `if` or `try`17blocks to decide whether to use a new or old pattern.1819If you do need to look at the version, use {func}`importlib.metadata.version`,20the standardized way to get versions for any installed Python package.2122## Changes in 8.22324### `ParamType` methods require `ctx`2526In 8.2, several methods of `ParamType` now have a `ctx: click.Context`27argument. Because this changes the signature of the methods from 8.1, it's not28obvious how to support both when subclassing or calling.2930This example uses `ParamType.get_metavar`, and the same technique should be31applicable to other methods such as `get_missing_message`.3233Update your methods overrides to take the new `ctx` argument. Use the34following decorator to wrap each method. In 8.1, it will get the context where35possible and pass it using the 8.2 signature.3637```python38import functools39import typing as t40import click4142F = t.TypeVar("F", bound=t.Callable[..., t.Any])4344def add_ctx_arg(f: F) -> F:45 @functools.wraps(f)46 def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:47 if "ctx" not in kwargs:48 kwargs["ctx"] = click.get_current_context(silent=True)4950 return f(*args, **kwargs)5152 return wrapper # type: ignore[return-value]53```5455Here's an example ``ParamType`` subclass which uses this:5657```python

`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489

line 58why, one step back
58class CommaDelimitedString(click.ParamType[str]):

Add a doc for supporting 8.1.x|8.2.0 (#2929)David Lordbefore adoption2d610e3

lines 59–62why, one step back
59 @add_ctx_arg
60 def get_metavar(self, param: click.Parameter, ctx: click.Context | None) -> str:61 return "TEXT,TEXT,..."62```