-
Notifications
You must be signed in to change notification settings - Fork 1
/
docfiller.py
1029 lines (843 loc) · 26.3 KB
/
docfiller.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Fill and share documentation (:mod:`~module_utilities.docfiller`)
=================================================================
"""
from __future__ import annotations
import inspect
from collections.abc import Mapping
from textwrap import dedent, indent
from typing import (
TYPE_CHECKING,
Iterable,
NamedTuple,
cast,
)
from . import cached
from ._doc import doc as _pd_doc
from .attributedict import AttributeDict
from .options import DOC_SUB
from .vendored.docscrape import NumpyDocString, Parameter
if TYPE_CHECKING:
from typing import (
Any,
Callable,
Sequence,
)
from .typing import F, NestedMap, NestedMapVal
def indent_docstring(
docstring: str | Callable[..., Any], prefix: str | None = "+ "
) -> str:
"""Create indented docstring"""
if callable(docstring):
docstring = (docstring.__doc__ or "").strip()
if prefix is not None:
return indent(docstring, prefix)
else:
return docstring
# Factory method to create doc_decorate
def doc_decorate(
*docstrings: str | Callable[..., Any] | None,
_prepend: bool = False,
**params: str,
) -> Callable[[F], F]:
"""
A decorator take docstring templates, concatenate them and perform string
substitution on it.
This decorator will add a variable "_docstring_components" to the wrapped
callable to keep track the original docstring template for potential usage.
If it should be consider as a template, it will be saved as a string.
Otherwise, it will be saved as callable, and later user __doc__ and dedent
to get docstring
Parameters
----------
*docstrings : str or callable
The string / docstring / docstring template to be appended in order
after default docstring under callable.
_prepend : bool, default=False
If True, prepend decorated function docstring. Otherwise, append to end.
**params
The string which would be used to format docstring template.
Notes
-----
Doc filling can be turned off by setting the environment variable
``DOCFILLER_SUB`` to one of ``0, f, false``.
Examples
--------
>>> @doc_decorate(type_='int')
... def func0(x, y):
... '''
... Parameters
... ----------
... x : {type_}
... x parameter.
... y : {type_}
... y parameter.
... Returns
... -------
... output : {type_}
... '''
... pass
>>> print(indent_docstring(func0))
+ Parameters
+ ----------
+ x : int
+ x parameter.
+ y : int
+ y parameter.
+ Returns
+ -------
+ output : int
To inherit from a function/docstring, pass it:
>>> @doc_decorate(func0, type_='float')
... def func1(x, y):
... pass
>>> print(indent_docstring(func1))
+ Parameters
+ ----------
+ x : float
+ x parameter.
+ y : float
+ y parameter.
+ Returns
+ -------
+ output : float
"""
if DOC_SUB:
return _pd_doc(*docstrings, _prepend=_prepend, **params)
else:
def decorated(func: F) -> F:
return func
return decorated
def _build_param_docstring(
name: str | None, ptype: str | None, desc: str | Sequence[str]
) -> str:
"""
Create multiline documentation of single name, type, desc.
Parameters
----------
name : str
Parameter Name
ptype : str
Parameter type
desc : list of str
Parameter description
Returns
-------
output : string
Multiline string for output.
"""
no_name = name is None or name == ""
no_type = ptype is None or ptype == ""
if no_name and no_type:
raise ValueError("must specify name or ptype")
elif no_type:
s = f"{name}"
elif no_name:
s = f"{ptype}"
else:
s = f"{name} : {ptype}"
if isinstance(desc, str):
if desc == "":
desc = []
else:
desc = [desc]
elif len(desc) == 1 and desc[0] == "":
desc = []
if len(desc) > 0:
desc = "\n ".join(desc)
s += f"\n {desc}"
return s
class TParameter(NamedTuple):
"""Interface to Parameters namedtuple in docscrape"""
name: str
type: str
desc: str
def _params_to_string(
params: str | list[str] | Parameter | list[Parameter] | tuple[Parameter, ...],
key_char: str = "|",
) -> str | dict[str, str]:
"""
Parse list of Parameters objects to string
Examples
--------
>>> from module_utilities.docfiller import Parameter
>>> p = Parameter(name="a", type="int", desc=["A parameter"])
>>> out = _params_to_string(p)
>>> print(out["a"])
a : int
A parameter
"""
if len(params) == 0:
return ""
if isinstance(params, Parameter):
params = [params]
if not isinstance(params, (list, tuple)):
params = [params]
if isinstance(params[0], str):
return "\n".join(cast("list[str]", params))
out: dict[str, str] = {}
for p in cast("list[TParameter]", params):
name = p.name
if key_char in name:
key, name = (x.strip() for x in name.split(key_char))
else:
key = name
out[key] = _build_param_docstring(name=name, ptype=p.type, desc=p.desc)
return out
def _parse_docstring(
func_or_doc: Callable[..., Any] | str, key_char: str = "|", expand: bool = True
) -> dict[str, str | dict[str, str]]:
"""
Parse numpy style docstring from function or string to dictionary.
Parameters
----------
func_or_doc : callable or str
If function, extract docstring from function.
key_char : str, default='|'
Character to split key_name/name
expand : bool, default=False
Returns
-------
parameters : dict
Dictionary with keys from docstring sections.
Notes
-----
the keys of ``parameters`` have the are the those of the numpy docstring,
but lowercase, and spaces replaced with underscores. The sections parsed are:
Summary, Extended Summary, Parameters, Returns, Yields, Notes,
Warnings, Other Parameters, Attributes, Methods, References, and Examples.
Examples
--------
>>> doc_string = '''
... Parameters
... ----------
... x : int
... x parameter
... y_alt | y : float
... y parameter
...
... Returns
... -------
... output : float
... an output
... '''
>>> p = _parse_docstring(doc_string)
>>> print(p["parameters"]["x"])
x : int
x parameter
>>> print(p["parameters"]["y_alt"])
y : float
y parameter
>>> print(p["returns"]["output"])
output : float
an output
>>> p2 = _parse_docstring(doc_string, expand=False)
>>> print(p2["Parameters"])
[Parameter(name='x', type='int', desc=['x parameter']), Parameter(name='y_alt | y', type='float', desc=['y parameter'])]
"""
if callable(func_or_doc):
doc = inspect.getdoc(func_or_doc)
else:
doc = func_or_doc
parsed = cast("dict[str, str | list[str] | list[Parameter]]", NumpyDocString(doc)._parsed_data) # type: ignore[no-untyped-call]
if expand:
parsed_out = {
k.replace(" ", "_").lower(): _params_to_string(parsed[k], key_char=key_char)
for k in [
"Summary",
"Extended Summary",
"Parameters",
"Returns",
"Yields",
"Notes",
"Warnings",
"Other Parameters",
"Attributes",
"Methods",
"References",
"Examples",
]
}
else:
parsed_out = cast("dict[str, str | dict[str, str]]", parsed)
return parsed_out
def dedent_recursive(data: NestedMap) -> NestedMap:
"""
Dedent nested mapping of strings.
Parameters
----------
data : dict
Returns
-------
output : object
Same type of ``data``, with dedented values
Examples
--------
>>> data = {
... 'a': {'value' : '''
... a : int
... A thing
... '''}}
>>> print(data['a']['value'])
<BLANKLINE>
a : int
A thing
<BLANKLINE>
>>> data = dedent_recursive(data)
>>> print(data['a']['value'])
a : int
A thing
"""
out: dict[str, NestedMapVal] = {}
for k in data:
v = data[k]
if isinstance(v, str):
v = dedent(v).strip()
else:
v = dedent_recursive(v)
out[k] = v
return out
def _recursive_keys(data: NestedMap) -> list[str]:
"""
Examples
--------
>>> d = {'a': 'a', 'b': {'c': "hello"}}
>>> _recursive_keys(d)
['a', 'b.c']
>>> d = {'a': 1}
>>> _recursive_keys(d)
Traceback (most recent call last):
...
ValueError: unknown type <class 'int'>
"""
keys: list[str] = []
for k, v in data.items():
if isinstance(v, dict):
key_list = [f"{k}.{x}" for x in _recursive_keys(v)]
elif isinstance(v, str):
key_list = [k]
else:
raise ValueError(f"unknown type {type(v)}")
keys.extend(key_list)
return keys
class DocFiller:
"""
Class to handle doc filling.
Parameters
----------
func_or_doc : callable or str
Docstring to parse. If callable, extract from function signature.
key_char : str, default='|'
Optional string to split name into key/name pair.
Examples
--------
>>> d = DocFiller.from_docstring(
... '''
... Parameters
... ----------
... x : int
... x param
... y : int
... y param
... z0 | z : int
... z int param
... z1 | z : float
... z float param
...
... Returns
... -------
... output0 | output : int
... Integer output.
... output1 | output : float
... Float output
... ''',
... combine_keys='parameters'
... )
...
>>> print(d.keys()[-4:])
['x', 'y', 'z0', 'z1']
>>> @d.decorate
... def func(x, y, z):
... '''
... Parameters
... ----------
... {x}
... {y}
... {z0}
... Returns
... --------
... {returns.output0}
... '''
... return x + y + z
...
>>> print(indent_docstring(func))
+ Parameters
+ ----------
+ x : int
+ x param
+ y : int
+ y param
+ z : int
+ z int param
+ Returns
+ --------
+ output : int
+ Integer output.
"""
def __init__(self, params: NestedMap | None = None) -> None:
self.data: dict[str, NestedMapVal]
if params is None:
self.data = {}
elif isinstance(params, dict):
self.data = params
else:
self.data = dict(params)
self._cache: dict[str, Any] = {}
def __repr__(self) -> str:
return f"{self.__class__.__name__}({repr(self.data)})"
def new_like(self, data: NestedMap | None = None) -> DocFiller:
"""Create new object with optional data."""
if data is None:
data = self.data.copy()
return type(self)(data)
def __getitem__(self, key: str) -> DocFiller | str:
val = self.data[key]
if isinstance(val, Mapping):
return self.new_like(val)
else:
return val
def dedent(self) -> DocFiller:
"""Recursively dedent params"""
return self.new_like(dedent_recursive(self.data))
@cached.meth
def keys(self) -> list[str]:
"""List of keys"""
return _recursive_keys(self.data)
def assign_combined_key(self, new_key: str, keys: Sequence[str]) -> DocFiller:
"""Combine multiple keys into single key"""
new = self.new_like()
new_data: list[str] = []
for k in keys:
d = self.data[k]
if isinstance(d, str):
new_data.append(d)
else:
raise ValueError(f"trying to combine key {k} with non-string value {d}")
new.data[new_key] = "\n".join(new_data)
return new
def _gen_get_val(self, key: str) -> Any:
from operator import attrgetter
f = attrgetter(key)
return f(self.params)
def assign_keys(self, **kwargs: str | Sequence[str]) -> DocFiller:
"""
Create new key from other keys.
Parameters
----------
**kwargs
new_key=old_key or new_key=[old_key0, old_key1, ...]
Note that dot notation is accepted.
Examples
--------
>>> d = DocFiller({'a0': 'a0', 'a1': 'a1', 'b': 'b'})
>>> dn = d.assign_keys(a='a0', c=['a0','b']).data
>>> print(dn['a'])
a0
>>> print(dn['c'])
a0
b
"""
new = self.new_like()
for new_key, old_keys in kwargs.items():
if isinstance(old_keys, str):
keys = [old_keys]
else:
keys = list(old_keys)
new.data[new_key] = "\n".join([self._gen_get_val(k) for k in keys])
return new
def assign_param(
self,
name: str,
ptype: str = "",
desc: str | list[str] | None = None,
key: str | None = None,
) -> DocFiller:
"""
Add in a new parameter
Parameters
----------
name : str
Parameters name
key : str, optional
Optional key for placement in `self`. This is like using `key | name`.
ptype : str, default=''
Optional type.
desc : str or list of str, default=''
Parameter description.
Returns
-------
output : DocFiller
New DocFiller instance.
Examples
--------
>>> d = DocFiller()
>>> dn = d.assign_param(
... name='x',
... ptype='float',
... desc='''
... A parameter
... with multiple levels
... ''',
... )
>>> print(dn['x'])
x : float
A parameter
with multiple levels
"""
new = self.new_like()
if desc is None:
desc = []
elif isinstance(desc, str):
# cleanup desc
desc = dedent(desc).strip().split("\n")
key = name if key is None else key
new.data[key] = _build_param_docstring(name=name, ptype=ptype, desc=desc)
return new
@classmethod
def concat(
cls,
*args: NestedMap | DocFiller,
**kwargs: NestedMap | DocFiller,
) -> DocFiller:
"""
Create new object from multiple DocFiller or dict objects.
Parameters
----------
*args
dict or Docfiller
**kwargs
dict or Docfiller objects
The passed name will be used as the top level.
Returns
-------
DocFiller
combined DocFiller object.
Notes
-----
Use unnamed `args` to pass in underlying data.
Use names ``kwargs`` to add namespace.
"""
# create
data: dict[str, NestedMapVal] = {}
def _update_data(x: DocFiller | NestedMap | dict[str, NestedMap]) -> None:
if isinstance(x, DocFiller):
# x = x.params
x = x.data
data.update(**x)
for a in args:
_update_data(a)
kws: dict[str, NestedMap] = {}
for k, v in kwargs.items():
if isinstance(v, DocFiller):
kws[k] = v.data
else:
kws[k] = v
_update_data(kws)
return cls(data)
def append(
self,
*args: Mapping[str, Any] | DocFiller,
**kwargs: Mapping[str, Any] | DocFiller,
) -> DocFiller:
"""Calls ``concat`` method with ``self`` as first argument."""
return type(self).concat(self, *args, **kwargs)
def insert_level(self, name: str) -> DocFiller:
"""Insert a level/namespace."""
return type(self)({name: self.data})
def levels_to_top(self, *names: str) -> DocFiller:
"""Make a level top level accessible"""
new = self.new_like()
for name in names:
d = self.data[name]
if isinstance(d, str):
raise ValueError(f"level {name} is not a dict")
else:
for k, v in d.items():
new.data[k] = v
return new
def rename_levels(self, **kws: str) -> DocFiller:
"""Rename a keys at top level."""
params = {}
for k, v in self.data.items():
key = kws.get(k, k)
params[key] = v
return self.new_like(params)
@cached.prop
def params(self) -> AttributeDict:
"""An AttributeDict view of parameters."""
return AttributeDict.from_dict(self.data, max_level=1)
# @cached.prop
# def atest(self) -> int:
# """
# A thing that does stuff
# Returns
# -------
# int
# """
# return 1
# @property
# def btest(self) -> int:
# """
# B thing that does stuff
# Returns
# -------
# int
# """
# return 2
@cached.prop
def _default_decorator(self) -> Callable[[F], F]:
return doc_decorate(**self.params)
def update(self, *args: Any, **kwargs: Any) -> DocFiller:
"""Update parameters"""
new = self.new_like()
new.data.update(*args, **kwargs)
return new
def assign(self, **kwargs: Any) -> DocFiller:
"""Assign new key/value pairs"""
return self.update(**kwargs)
def decorate(self, func: F) -> F:
"""
Default decorator.
This uses `self.params` and the decorated function docstring as a template.
If need to pass parameters, use self.__call__
See Also
--------
__call__
"""
return self._default_decorator(func)
def __call__(
self,
*templates: Callable[..., Any] | str,
_prepend: bool = False,
**params: str,
) -> Callable[[F], F]:
"""
Factory function to create docfiller decorator.
This should always be used in a callable manner.
If want to call without any parameter use decorate()
Parameters
----------
*templates : callable
docstrings to be used as templates.
_prepend : bool, default=False
If `True`, then prepend `templates` with docstring of decorated function.
Otherwise, append to end.
**params
Extra parameters to be substituted.
Example
-------
Using the default decorator
>>> d = DocFiller({"x": "hello", "y": "there"})
>>> @d.decorate
... def func():
... '''
... A function with x={x} and y={y}
... '''
... pass
>>> print(indent_docstring(func))
+ A function with x=hello and y=there
Using call without args
>>> @d()
... def func1():
... '''
... A new function with x={x} and y={y}
... '''
... pass
>>> print(indent_docstring(func1))
+ A new function with x=hello and y=there
Using call with args. This inherits from passed template
>>> @d(func, x="new_x")
... def func2():
... pass
>>> print(indent_docstring(func2))
+ A function with x=new_x and y=there
"""
ntemplates, nparams = len(templates), len(params)
if ntemplates == nparams == 0 and not _prepend:
return self.decorate
elif nparams == 0:
return doc_decorate(*templates, _prepend=_prepend, **self.params)
else:
return self.update(params)(*templates, _prepend=_prepend)
def inherit(
self,
template: Callable[..., Any],
_prepend: bool = False,
**params: str,
) -> Callable[[F], F]:
"""
Factor function to create decorator.
Use combination of docstring_inheritance.inherit_numpy_docstring and
DocFiller.
Parameters
----------
template : callable
Template method to inherit from.
_prepend : bool, default=False
Prepend parameter.
**params :
Extra parameter specificiations.
Returns
-------
decorator : callable
Decorator
See Also
--------
~module_utilities.docinherit.doc_inherit
"""
from . import docinherit
docfiller = self.update(params)
def decorator(func: F) -> F:
@docfiller(template)
def dummy() -> None: # pragma: no cover
pass
func = docfiller(_prepend=_prepend)(func)
return docinherit.doc_inherit(parent=dummy)(func)
return decorator
def factory_from_parent(
self,
cls: type,
) -> Callable[..., Callable[[F], F]]:
"""
Interface to docinherit.factory_docfiller_from_parent.
Parameters
----------
cls : type
Class to inherit from.
See Also
--------
~module_utilities.docinherit.factory_docfiller_from_parent
"""
from . import docinherit
return docinherit.factory_docfiller_from_parent(cls, self)
def factory_inherit_from_parent(
self,
cls: type,
) -> Callable[..., Callable[[F], F]]:
"""
Interface to docinherit.factory_docfiller_inherit_from_parent.
Parameters
----------
cls : type
Class to inherit from
See Also
--------
~module_utilities.docinherit.factory_docfiller_inherit_from_parent
"""
from . import docinherit
return docinherit.factory_docfiller_inherit_from_parent(cls, self)
@classmethod
def from_dict(
cls,
params: Mapping[str, Any],
namespace: str | None = None,
combine_keys: str | Sequence[str] | None = None,
keep_keys: bool | str | Sequence[str] = True,
key_map: Mapping[str, str] | Callable[[str], str] | None = None,
) -> DocFiller:
"""
Create a Docfiller instance from a dictionary.
Parameters
----------
params : mapping
namespace : str, optional
Top level namespace for DocFiller.
combine_keys : str, sequence of str, mapping, optional
If str or sequence of str, Keys of ``params`` to at the top level.
If mapping, should be of form {namespace: key(s)}
keep_keys : str, sequence of str, bool
If False, then don't keep any keys at top level. This is useful with the ``combine_keys`` parameter.
If True, keep all keys, regardless of combine_keys.
If str or sequence of str, keep these keys in output.
key_map : mapping or callable
Function or mapping to new keys in resulting dict.
Returns
-------
DocFiller
"""
if not keep_keys:
keep_keys = []
elif keep_keys is True:
keep_keys = [k for k in params]
elif isinstance(keep_keys, str):
keep_keys = [keep_keys]
assert isinstance(keep_keys, Iterable)
if combine_keys:
if isinstance(combine_keys, str):
combine_keys = [combine_keys]
updated_params = {k: params[k] for k in keep_keys}
# if isinstance(combine_keys, (list, tuple)):
# combine_keys = {'': combine_keys}
# for k, v in combine_keys.items():
# if k in updated_params:
# updated_params =
for k in combine_keys:
updated_params.update(**params[k])
else:
updated_params = {k: params[k] for k in keep_keys}
if key_map is None:
pass
elif callable(key_map):
updated_params = {key_map(k): v for k, v in updated_params.items()}
else:
assert isinstance(key_map, Mapping)
updated_params = {key_map[k]: v for k, v in updated_params.items()}
if namespace:
updated_params = {namespace: updated_params}
return cls(params=updated_params)
@classmethod
def from_docstring(
cls,
func_or_doc: Callable[..., Any] | str,
namespace: str | None = None,
combine_keys: str | Sequence[str] | None = None,
key_char: str = "|",
keep_keys: bool | str | Sequence[str] = True,
key_map: Mapping[str, str] | Callable[[str], str] | None = None,
) -> DocFiller:
"""
Create a Docfiller instance from a function or docstring.
Parameters
----------
func_or_doc : str or callable
Docstring to parse to get parameters.
namespace : str, optional
Top level namespace for DocFiller.
combine_keys : str, sequence of str, mapping, optional