Skip to content

Commit e63a3c7

Browse files
authored
Modify docstrings of wrapped functions. (#61)
List args and kwargs names that will be rewritten by cf_xarray if asked to and if possible.
1 parent 98c84fe commit e63a3c7

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

cf_xarray/accessor.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,38 @@ def _guess_bounds_dim(da):
365365
return result
366366

367367

368+
def _build_docstring(func):
369+
"""
370+
Builds a nice docstring for wrapped functions, stating what key words
371+
can be used for arguments.
372+
"""
373+
374+
# this list will need to be updated any time a new mapper is added
375+
mapper_docstrings = {
376+
_get_axis_coord: f"One or more of {(_AXIS_NAMES + _COORD_NAMES)!r}",
377+
_get_axis_coord_single: f"One of {(_AXIS_NAMES + _COORD_NAMES)!r}",
378+
_get_measure_variable: f"One of {_CELL_MEASURES!r}",
379+
}
380+
381+
sig = inspect.signature(func)
382+
string = ""
383+
for k in set(sig.parameters.keys()) & set(_DEFAULT_KEY_MAPPERS):
384+
mappers = _DEFAULT_KEY_MAPPERS.get(k, [])
385+
docstring = "; ".join(
386+
mapper_docstrings.get(mapper, "unknown. please open an issue.")
387+
for mapper in mappers
388+
)
389+
string += f"\t\t{k}: {docstring} \n"
390+
391+
for param in sig.parameters:
392+
if sig.parameters[param].kind is inspect.Parameter.VAR_KEYWORD:
393+
string += f"\t\t{param}: {mapper_docstrings[_get_axis_coord]} \n\n"
394+
return (
395+
f"\n\tThe following arguments will be processed by cf_xarray: \n{string}"
396+
"\n\t----\n\t"
397+
)
398+
399+
368400
def _getattr(
369401
obj: Union[DataArray, Dataset],
370402
attr: str,
@@ -443,6 +475,8 @@ def wrapper(*args, **kwargs):
443475

444476
return result
445477

478+
wrapper.__doc__ = _build_docstring(func) + wrapper.__doc__
479+
446480
return wrapper
447481

448482

cf_xarray/tests/test_accessor.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,3 +383,8 @@ def test_add_bounds(obj, dims):
383383
assert name in added.coords
384384
assert added[dim].attrs["bounds"] == name
385385
assert_allclose(added[name].reset_coords(drop=True), expected[dim])
386+
387+
388+
def test_docstring():
389+
assert "One of ('X'" in airds.cf.groupby.__doc__
390+
assert "One or more of ('X'" in airds.cf.mean.__doc__

0 commit comments

Comments
 (0)