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 fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# Supporting Multiple Versions
If you are a library maintainer, you may want to support multiple versions ofClick. See the Pallets [version policy] for information about our versionnumbers and support policy.
[version policy]: https://palletsprojects.com/versions
Most features of Click are stable across releases, and don't require specialhandling. However, feature releases may deprecate and change APIs. Occasionally,a change will require special handling.
## Use Feature Detection
Prefer using feature detection. Looking at the version can be tempting, but isoften more brittle or results in more complicated code. Try to use `if` or `try`blocks to decide whether to use a new or old pattern.
If you do need to look at the version, use {func}`importlib.metadata.version`,the standardized way to get versions for any installed Python package.
## Changes in 8.2
### `ParamType` methods require `ctx`
In 8.2, several methods of `ParamType` now have a `ctx: click.Context`argument. Because this changes the signature of the methods from 8.1, it's notobvious how to support both when subclassing or calling.
This example uses `ParamType.get_metavar`, and the same technique should beapplicable to other methods such as `get_missing_message`.
Update your methods overrides to take the new `ctx` argument. Use thefollowing decorator to wrap each method. In 8.1, it will get the context wherepossible and pass it using the 8.2 signature.
```pythonimport functoolsimport typing as timport click
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
def add_ctx_arg(f: F) -> F: @functools.wraps(f) def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any: if "ctx" not in kwargs: kwargs["ctx"] = click.get_current_context(silent=True)
return f(*args, **kwargs)
return wrapper # type: ignore[return-value]```
Here's an example ``ParamType`` subclass which uses this:
```pythonclass CommaDelimitedString(click.ParamType[str]): @add_ctx_arg def get_metavar(self, param: click.Parameter, ctx: click.Context | None) -> str: return "TEXT,TEXT,..."```