generate python docstring template using current argument list

4.4k views Asked by At

I have a python package to release soon, so now I begin to slowly add docstrings to the files using vim. So for a func like

def foo(x, y, z=None, **kwargs):

I have to manually type the following repetitively for a whole day

""" foo does this stuff.

Parameters
----------
x: 
y:
z: optional
kwargs:

Returns
-------

"""

Is there a way to dynamically generate this template docstring by defining some vim macros (which I know nothing of, so a suggestion for how to start would be great as well). Thanks.

3

There are 3 answers

0
nye17 On BEST ANSWER

The author of vim-pydocstring has kindly added the compatibility with Numpy-style docstrings to the package, which now seems to be the best answer to this question.

You can pull/download the vim plugin from here

0
romainl On

Macros are just normal actions recorded in a register and played back without delay.

One possible strategy would be to:

  1. start recording,
  2. duplicate that line above itself,
  3. do all the needed manipulations,
  4. stop recording,
  5. play that macro back for every def line.

It would look like that:

qq
yyP
(all your text manipulations)
q
:g/def /normal! @q
1
Ingo Karkat On

Repeating the function name and arguments usually isn't the big deal (and insert-mode completion helps here); rather, you want a consistent skeleton where you just have to insert the variable information at the right places.

snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki.

There are three things to evaluate: First, the features of the snippet engine itself, second, the quality and breadth of snippets provided by the author or others; third, how easy it is to add new snippets. With some advanced engines, you may even get extraction of the function and argument names itself.