Skip to content

Commit 2d610e3

Browse files
authored
Add a doc for supporting 8.1.x|8.2.0 (#2929)
2 parents 134951f + 55189e3 commit 2d610e3

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

docs/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ How to Guides
8080

8181
entry-points
8282
setuptools
83+
support-multiple-versions
8384

8485
Conceptual Guides
8586
^^^^^^^^^^^^^^^^^^^

docs/support-multiple-versions.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Supporting Multiple Versions
2+
3+
If you are a library maintainer, you may want to support multiple versions of
4+
Click. See the Pallets [version policy] for information about our version
5+
numbers and support policy.
6+
7+
[version policy]: https://palletsprojects.com/versions
8+
9+
Most features of Click are stable across releases, and don't require special
10+
handling. However, feature releases may deprecate and change APIs. Occasionally,
11+
a change will require special handling.
12+
13+
## Use Feature Detection
14+
15+
Prefer using feature detection. Looking at the version can be tempting, but is
16+
often more brittle or results in more complicated code. Try to use `if` or `try`
17+
blocks to decide whether to use a new or old pattern.
18+
19+
If you do need to look at the version, use {func}`importlib.metadata.version`,
20+
the standardized way to get versions for any installed Python package.
21+
22+
## Changes in 8.2
23+
24+
### `ParamType` methods require `ctx`
25+
26+
In 8.2, several methods of `ParamType` now have a `ctx: click.Context`
27+
argument. Because this changes the signature of the methods from 8.1, it's not
28+
obvious how to support both when subclassing or calling.
29+
30+
This example uses `ParamType.get_metavar`, and the same technique should be
31+
applicable to other methods such as `get_missing_message`.
32+
33+
Update your methods overrides to take the new `ctx` argument. Use the
34+
following decorator to wrap each method. In 8.1, it will get the context where
35+
possible and pass it using the 8.2 signature.
36+
37+
```python
38+
import functools
39+
import typing as t
40+
import click
41+
42+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
43+
44+
def 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)
49+
50+
return f(*args, **kwargs)
51+
52+
return wrapper # type: ignore[return-value]
53+
```
54+
55+
Here's an example ``ParamType`` subclass which uses this:
56+
57+
```python
58+
class CommaDelimitedString(click.ParamType):
59+
@add_ctx_arg
60+
def get_metavar(self, param: click.Parameter, ctx: click.Context | None) -> str:
61+
return "TEXT,TEXT,..."
62+
```

0 commit comments

Comments
 (0)