Skip to content

Commit e6f6c87

Browse files
committed
new post / 2024-11-10-python-adding-version-info-to-docstrings.md
1 parent 7c6bb19 commit e6f6c87

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
authors:
3+
- copdips
4+
categories:
5+
- python
6+
comments: true
7+
date:
8+
created: 2024-11-10
9+
---
10+
11+
# Python adding version info to docstrings
12+
13+
When checking PySpark's source code, find a nice way it uses to add version information to docstrings by a [@since()](https://github.com/apache/spark/blob/5d757993f4cfcd859eb11640d210a560d6136465/python/pyspark/__init__.py#L81-L97) decorator. Here is an example:
14+
15+
<!-- more -->
16+
17+
```python title="decorator since defined in pypsark.since"
18+
# https://github.com/apache/spark/blob/5d757993f4cfcd859eb11640d210a560d6136465/python/pyspark/__init__.py#L81-L97
19+
20+
_F = TypeVar("_F", bound=Callable)
21+
22+
def since(version: Union[str, float]) -> Callable[[_F], _F]:
23+
"""
24+
A decorator that annotates a function to append the version of Spark the function was added.
25+
"""
26+
import re
27+
28+
indent_p = re.compile(r"\n( +)")
29+
30+
def deco(f: _F) -> _F:
31+
assert f.__doc__ is not None
32+
33+
indents = indent_p.findall(f.__doc__)
34+
indent = " " * (min(len(m) for m in indents) if indents else 0)
35+
f.__doc__ = f.__doc__.rstrip() + "\n\n%s.. versionadded:: %s" % (indent, version)
36+
return f
37+
38+
return deco
39+
```
40+
41+
```python title="usage of since decorator in delta.tables"
42+
# https://github.com/apache/spark/blob/5d757993f4cfcd859eb11640d210a560d6136465/python/pyspark/ml/tuning.py#L191-L205
43+
44+
@since("1.4.0")
45+
def build(self) -> List["ParamMap"]:
46+
"""
47+
Builds and returns all combinations of parameters specified
48+
by the param grid.
49+
"""
50+
```
51+
52+
This will generate the following docstring for the `build` method when using `help(build)` in the Python REPL:
53+
54+
```python
55+
"""
56+
Builds and returns all combinations of parameters specified
57+
by the param grid.
58+
59+
.. versionadded:: 1.4.0
60+
"""
61+
```

0 commit comments

Comments
 (0)