heavenshell / vim-pydocstring Goto Github PK
View Code? Open in Web Editor NEWGenerate Python docstring to your Python source code.
License: BSD 3-Clause "New" or "Revised" License
Generate Python docstring to your Python source code.
License: BSD 3-Clause "New" or "Revised" License
In my multi.txt I have:
{{indent}}'''
{{header}}
{{indent}}Args:
{{nested_indent}}{{args}}:
{{indent}}'''
see also #2
Hi again,
I'm testing this plugin at the moment and I think it's really great. I however noted something is missing.
Is it possible to list all the exceptions that can be raised in a function/method?
Something like that:
def module_level_function(param1, param2=None, *args, **kwargs):
"""This is an example of a module level function.
Function parameters should be documented in the ``Args`` section. The name
of each parameter is required. The type and description of each parameter
is optional, but should be included if not obvious.
Args:
param1 (int): The first parameter.
param2 (:obj:`str`, optional): The second parameter. Defaults to None.
Second line of description should be indented.
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
Returns:
bool: True if successful, False otherwise.
The return type is optional and may be specified at the beginning of
the ``Returns`` section followed by a colon.
The ``Returns`` section may span multiple lines and paragraphs.
Following lines should be indented to match the first line.
The ``Returns`` section supports any reStructuredText formatting,
including literal blocks::
{
'param1': param1,
'param2': param2
}
Raises:
AttributeError: The ``Raises`` section is a list of all exceptions
that are relevant to the interface.
ValueError: If `param2` is equal to `param1`.
That's an example I took from here:
http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
I have installed Pydocstring with Vundle (below of this message there is a copy paste of my whole .vimrc file).
When I define a class, put the cursor at the end of the definition of this class (at the colon), and write :Pydocstring
, only the template of the description appears, the list of arguments that I add to the class are not listed. Below an example of what happens in my console.
:param arg1:
and :param arg2:
are not automatically added by Pydocstring
I have VIM version 8.1.177, and I'm up to date with the master branch of Pydocstring.
My .vimrc :
set nocompatible " required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
" add all your plugins here (note older versions of Vundle
" used Bundle instead of Plugin)
Plugin 'w0rp/ale'
Plugin 'nvie/vim-flake8'
Plugin 'google/yapf'
Plugin 'Valloric/YouCompleteMe'
Plugin 'vim-scripts/indentpython.vim'
Plugin 'heavenshell/vim-pydocstring'
" All of your Plugins must be added before the following line
call vundle#end() " required
filetype plugin indent on " required
set encoding=utf-8
hi pythonSelf ctermfg=68 guifg=#5f87d7 cterm=bold gui=bold
" Enable folding
set foldmethod=indent
set foldlevel=99
" Enable folding with the spacebar
noremap <space> za
" PEP8 indentation
au BufNewFile,BufRead *.test set tabstop=4
\softtabstop=4
\shiftwidth=4
\textwidth=80
\expandtab
\autoindent
\fileformat=unix
set wrap
set textwidth=80
let python_highlight_all=1
syntax on
set ruler "for column numbers
" Set this. Airline will handle the rest.
let g:airline#extensions#ale#enabled = 1
"let g:ale_sign_column_always = 1
"let g:ycm_python_binary_path = '~/anaconda3/bin/python'
"let g:ycm_python_binary_path = '~/anaconda2/bin/python'
"split navigations
set splitbelow
set splitright
nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>
with and without autocmd FileType python setlocal tabstop=4 shiftwidth=4 softtabstop=4 expandtab
results are like this only:
def foo(a, b, c):
"""foo
:param a:
:param b:
:param c:
"""
Input from anyone would be helpful.
I am trying to setup vim-pydocstring on Windows. But so far no success.
Vim version:
VIM - Vi IMproved 8.1 (2018 May 18, compiled Oct 12 2019 22:02:45)
MS-Windows 64-bit console version
doq is installed with pip install doq:
λ pip show doq
Name: doq
Version: 0.6.0
Summary: Docstring generator
Home-page: http://github.com/heavenshell/py-doq
Author: Shinya Ohyanagi
Author-email: [email protected]
License: BSD
Location: c:\users\user\appdata\local\programs\python\python37\lib\site-packages
Requires: parso, jinja2
Required-by:
Doq is working when performing command from command line:
λ python -m doq.cli -f fraction.py -w
But when trying to do it from vim - it is reporting that doq is not installed.
Setup in vimrc related to pydocstring:
"Plugin Pydocstring setup {{{
let g:pydocstring_doq_path = 'c:/users/user/appdata/local/programs/pytho/python37/lib/site-packages/doq'
nmap <silent> <F12> <Plug>(pydocstring)
"}}}
First thanks for the great plug-in, it really improves my code quality.
However, it sadly doesn't sufficiently support numpy-style
docstrings. Or at least I am too stupid to configure it properly.
So far I look into the examples in the test
directory and played around, but it either works for annotated arguments, or arguments which are not annotated, never for both.
What I optimally want is:
"""
_header_.
Parameters
---------------
_arg_name_ : {opt _type_}
_arg_name_ is
Returns
----------
_header_ : {opt _return_type_}
"""
The problems I face:
{{_header_}
with the {{_return_type_}}
keyword (really minor problem, using returnVar
instead is not all that bad {{_args_}} : {{_lf_}}{{_nested_indent_}}{{_args_}} is
in multiline
; {{_name_}} : {{_type_}}
in arg
{{_args_}} : {{_type_}}{{_lf_}}{{_nested_indent_}}{{_name_}} is
in arg
; {{_args_}}
in mutliline
I think making {{_name_}}
(maybe as _arg_name
?) and {{_type_}}
(as _arg_type
?) available in multiline
should solve the second problem.
I was looking at the template multi, apparently there is a line for return type named rtype. The standard doc string is usually :return in python. Moreover, it seems I only get :param but not :return or :rtype (as in the template). Am I missing something here? If not can do a PR for :return generation?
I sometimes trigger vim-docstring right after typing the function declaration, i.e., with just one line of
def foo(a):
in this case, the plugin will place the docstring generated on top of the line rather than below. Is this deliberate or a bug?
Funny thing is, I first found this when I was adding docstring for my init function inside a class, and the placement happened to be exactly what I want --- doc right below
class foo(object):
rather than below
def __init___(self):
which is one indentation level lower.
So if possible, I'd be happy to see this feature kept....Thanks.
I have installed vim-pydocstring with Vundle and when I run it on a method I get the below error.
Error detected while processing function pydocstring#insert..<SNR>112_builddocstring:
line 33:
E706: Variable type mismatch for: argTemplate
Press ENTER or type command to continue
I'm trying to make a template for Google style doc string. Here is my multi.txt:
"""{{_header_}}
{{_indent_}}Args:
{{_nested_indent_}}{{_args_}}:
{{_indent_}}Returns:
{{_return_type_}}
"""
It produces this:
def my_func(self, nbr: int, word: str) -> bool:
"""my_func
Args:
nbr (int):
word (str):
Returns:
bool
"""
Note that the return type is not indented (expected behaviour). Now I try to indent it:
multi.txt:
"""{{_header_}}
{{_indent_}}Args:
{{_nested_indent_}}{{_args_}}:
{{_indent_}}Returns:
{{_nested_indent_}}{{_return_type_}}
"""
def my_func(self, nbr: int, word: str) -> bool:
"""my_func
Args:
nbr (int):
word (str):
Returns:
{{_nested_indent_}}bool
"""
The placeholder appears in the code. Same result with the indent placeholder.
Hello.I am using neovim and I have installed doq.And I have set g:pydocstring_doq_path in my init.vim.But when i try to call :Pydocstring,the error as the title said happens.How should I make it work?please help
How should I do this?? I am using 1.0.0 on vim 7.4.
$which doq
/home/user/anaconda3/bin/doq
in vim I use
let g:pydocstring_doq_path. = '/home/user/anaconda3/bin/doq'
then when I try :Pydocstring
I get this
Error detected while processing function pydocstring#insert[31]..<SNR>34_execute:
line 12:
E121: Undefined variable: c
E116: Invalid arguments for function job_start(a:cmd, { 'callback': {c, m -> a:cb(c, m, a:indent, a:start_lineno)}, 'exit_cb': {c, m -> a:ex_cb(c, m)}, 'in_mode': 'nl', })
E15: Invalid expression: job_start(a:cmd, { 'callback': {c, m -> a:cb(c, m, a:indent, a:start_lineno)}, 'exit_cb': {c, m -> a:ex_cb(c, m)}, 'in_mode': 'nl', })
def foo(arg1, arg2):
pass
def foo(arg1, arg2):
"""foo
:param arg1
:param arg2
"""
pass
def foo(arg1, arg2):
"""foo
:param arg1:
:param arg2:
"""
pass
If a line is commented inside in the list of arguments, we get an incomplete docstring.
minimal example:
def get_adjacency(
facets,
points=None,
max_degree=None,
# num_verts=2,
n_verts=3,
):
"""get_adjacency
:param facets:
:param points:
:param max_degree:
"""
Where we can see that the argument parsing stops at the first encountered comment.
(This is not at all urgent, I just posted the issue for posterior documentation)
When opening a python file in neovim, I receive the following error message:
Error detected while processing /home/chris/.config/nvim/plugged/vim-pydocstring/ftplugin/python/pydocstring.vim
line 13:
+channel and +job are required for pydocstring.vim
Do I need to do something first to create channel and job values?
Hi, just found your plugin which will save me a lot of time.
However I did one quick change in your code in order to keep the default indentation of the block even when the template contains more than keywords. Patch is below.
diff --git a/autoload/pydocstring.vim b/autoload/pydocstring.vim
index 19d3f23..14e6645 100644
--- a/autoload/pydocstring.vim
+++ b/autoload/pydocstring.vim
@@ -99,7 +99,7 @@ function! s:builddocstring(strs, indent)
elseif line == '"""'
call add(docstrings, a:indent . line)
else
- call add(docstrings, line)
+ call add(docstrings, a:indent . line)
endif
endfor
let tmpl = substitute(join(docstrings, "\n"), "\n$", '', '')
I also think it would be cleaner to put everything into ftplugins/python so that you do not load your plugin when you do not need it.
Is it trivial to add support for numpy style docstring like
Parameters
----------------
x : float
x is this stuff.
Returns
-----------
y : float
y is that stuff.
I just noticed that a signature of the form
def moment(weights: tuple, coords: numpy.ndarray) -> numpy.ndarray:
results in the following docstring
"""moment
:param weights:
:type weights: tuple
:param coords:
:type coords: numpy.ndarray
:rtype: numpyndarray
"""
where the period has been stripped from numpy.ndarray
in the return type. It's easy to work around, but I thought I'd register my observation here in case you weren't aware.
Nice plugin, by the way! Very useful.
def func(a: int, b, c):
pass
def func(a: int, b, c):
"""func
:param a:
:type a: int
:param c:
"""
pass
b
is missing.
hi,
I was wondering if it was possible to update the docstring in case a function is modified ?
Currently, if I write a function, add a docstring, and then add an argument, if I rerun :Pydocstring, they get imbricated.
Thanks !
Would it be possible to have a upgrade function? I created the function and inserted the docstring, then I modfie the first line to be some description.
Now I add some parameters and recreate the docstring, what would be great is that the current docstring be deleted, but the first line (and maybe until the parameter definition and text after the parameters) be kept intact.
best
See also #2
Hi,
I think this plugin is great, it seems to be an equivalent to autoDocstring for VScode.
As you might have seen in the issues, people ask for other docstring styles (ex: Google, numpy) than the default one.
Would it be possible to setup an option, so the users could choose (in their vimrc) which template to use?
Best
Thank you for making and sharing this. Is there a way to easily extend this package to Google style?
I have this function:
def addInputPercentage(
self,
name: str,
height_per: float = 100,
angle: float = 180,
diameter: Optional[float] = None,
external: bool = False,
) -> None:
And generating a docstring with this plugin yielded:
"""addInputPercentage
Args:
name (str):
100:
180:
diameter (Optional[float]):
None:
False:
Returns:
None
"""
The default value for the type-hinted argument was used instead of the argument's name in the docstring.
I think it's a bug.
e.g.
def foo(arg1, arg2: List[int, str]=[1, 'foo']) -> None:
pass
{
"name": "foo",
"args": [
{ "arg": "arg1", "type": "", "default": ""},
{ "arg": "arg2", "type": "List[int, str]", "default": "[1, 'foo']"},
],
"rtype": "None"
}
It would be great to have a separate variable in the layout so we can make a proper numpy layout.
This would be great:
{{_indent_}}Parameters
{{_indent_}}------------
{{_args_}} : {_type_}
{{_indent_}} {{_args_}} is
{{_indent_}}Returns
{{_indent_}}--------
But at the moment if you have a function with typing then it messes everything up.
I tried installing using vim plug:
Plug 'heavenshell/vim-pydocstring', { 'do': 'make install' }
but I got this error:
doq
not found. Install doq
I also checked to see if doq was installed by following the above command (docs made it sound like it would be automatically installed) but it wasn't. So I install doq via pip into my conda environment, but it still returned the same error. I tried setting the path to doq manually, but I'm not super familiar with the vim syntax for doing so, so maybe I got something wrong there.
Currently Noevim does not support.
I don't have any Neovim env and knowledge.
So I'm very appricated to someone send me PR 😉
job_start
. Neovim's use jobstart
Apparently, when looking at the multi.txt, the :rtype: would be generated as well.
Yet I cannot generate a docstring containing a rtype.. how is this done?
ftplugin/python/pydocstring.vim:13
all time see that error when open python file =(
nv -v
NVIM v0.5.0-7fef0f8db
Build type: Release
LuaJIT 2.0.5
Compilation: /usr/local/Homebrew/Library/Homebrew/shims/mac/super/clang -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -DNDEBUG -DMIN_LOG_LEVEL=3 -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wmissing-prototypes -Wimplicit-fallthrough -Wvla -fstack-protector-strong -fdiagnostics-color=auto -DINCLUDE_GENERATED_DECLARATIONS -D_GNU_SOURCE -DNVIM_MSGPACK_HAS_FLOAT32 -DNVIM_UNIBI_HAS_VAR_FROM -I/tmp/neovim-20191128-44866-1ykypi9/build/config -I/tmp/neovim-20191128-44866-1ykypi9/src -I/usr/local/include -I/tmp/neovim-20191128-44866-1ykypi9/deps-build/include -I/usr/local/opt/gettext/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include -I/tmp/neovim-20191128-44866-1ykypi9/build/src/nvim/auto -I/tmp/neovim-20191128-44866-1ykypi9/build/include
Compiled by User
Features: +acl +iconv +tui
See ":help feature-compile"
system vimrc file: "$VIM/sysinit.vim"
fall-back for $VIM: "/usr/local/Cellar/neovim/HEAD-7fef0f8/share/nvim"
Run :checkhealth for more info
OS: 64bit Mac OS X 10.15.3 19D76
Kernel: x86_64 Darwin 19.3.0
Uptime: 1h 50m
Packages: 544
Shell: zsh 5.8
Resolution: 2880x1800 ,1920x1080 ,1920x1080
DE: Aqua
WM: Quartz Compositor
WM Theme: Graphite (Dark)
Disk: 12G / 500G (27%)
CPU: Intel Core i7-7820HQ @ 2.90GHz
GPU: Radeon Pro 560 / Intel HD Graphics 630
RAM: 7686MiB / 16384MiB
Hi @heavenshell ,
I wanted to add custom template for docstring.
I followed template shown in Readme.rst
I copied contents from tests/templates/class.txt to another custom file (/root/.pydocstring/python_commenter.txt)
Following are the contents my .vimrc
" Store pydocstring path and template path
nmap <silent> <C-_> <Plug>(pydocstring)
let g:pydocstring_doq_path = '/usr/local/bin/doq'
let g:pydocstring_templates_path = '/root/.pydocstring/python_commenter.txt'
Following are the contents and permission of python_commenter.txt
root@geek:~/source/ksa_tests# cat /root/.pydocstring/python_commenter.txt
"""{{ name }}.
"""
root@geek:~/source/ksa_tests# ls -l /root/.pydocstring/python_commenter.txt
-rw-r--r-- 1 root root 19 Mar 29 07:22 /root/.pydocstring/python_commenter.txt
However when I open Python file using vim and try to do :Pydocstring
I get following error
Error detected while processing function <lambda>1[1]..<SNR>105_callback:
line 1:
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
E899: Argument of reverse() must be a List or Blob
E474: Invalid argument
-- More --
I searched for reverse in this repository and found one occurance in
line 51 of /autoload/pydocstring.vim
Based on error, I think json_decode(a:msg) is not returning List or Blob, whereas reverse() requires List of Blob.
Please let me know whether this information was enough or you want some more information in order to reproduce this issue.
Or I am doing this in a wrong way.
Thanks!
If you add type hinting with default values, the doc string created is messed up:
def get_last(self, product: str = None):
"""get_last
:param None:
"""
if not product:
product = self._default_product
Newbie thing, but how to overwrite default mapping is missing from doc.
As outlined in the help text, I put
"""{{_header_}}
{{_arg_}} :{{_lf_}}{{_indent_}} {{_arg_}} is
"""
in multi.txt
.
When running :Pydocstring
, this is the result:
def foo(a, b, c):
"""foo
{{_arg_}} :{{_lf_}} {{_arg_}} is
"""
pass
I have a function with types in the definition like:
def my_func(x: str, y:str) -> str:
My preference would be for the generated docstring to not have the lines type
and rtype
(type are a bit redundant). I looked in the docs for a way to disable those lines being generated, but I could not find it. Is there a way to do this?
Should be snake_case.
If a default parameter is a dict, I get a wrong default docstring.
minimal example:
def get_adjacency(
facets,
points=None,
max_degree=None,
dtypes={"ints": np.int64, "floats": np.float32},
):
"""get_adjacency
:param facets:
:param points:
:param max_degree:
:param dtypes:
:param "floats":
:type "floats": np.float32}
"""
where we can see that it has considered "float" as a default parameter and default type
arg type, return type.
Hello.
If I want to set variables, e.g. for doq installation or my template files, I have to type full path like this.
let g:pydocstring_doq_path = '/home/user/.local/bin/doq'
Using the tilda for home does not work and :Pydocstring command complains that it cannot find doq.
let g:pydocstring_doq_path = '~/.local/bin/doq " doesn't work'
Similar is true for template_path
let g:pydocstring_templates_dir = '~/.vim/template_files/pydocstring_google_style' " works
let g:pydocstring_templates_path = '/home/user/.vim/template_files/pydocstring_google_style' " doesn't work
I think the first way is more portable for sharing dotfiles. Do you agree? Is a problem somewhere else?
Thank you.
Hi @heavenshell ,
I'm try to use fatastic plugin, but when call function for generate docstring, Vim (neovim) show me weird error about job_start
function not defined.
Can you advice me about this error ?
Unable to insert the docstring. Getting the mentioned error.
Pydocstring contains a CLI function that return a autogenerated docstring in multiples formats.
Only need call from bash cli.
Example:
pydocstring -f numpy ../core/models/personas.py 49,0
this generate this exit:
"""
Attributes
----------
user : TYPE
models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
primer_nombre : TYPE
models.CharField(max_length=20, db_index=True)
segundo_nombre : TYPE
models.CharField(max_length=20, db_index=True, blank=True)
primer_apellido : TYPE
models.CharField(max_length=20, db_index=True)
segundo_apellido : TYPE
models.CharField(
max_length=20, db_index=True, blank=True, null=True)
fecha_nacimiento : TYPE
models.DateField(blank=True, null=True)
rh : TYPE
models.CharField(max_length=3, blank=True)
genero : TYPE
models.CharField(max_length=1, blank=True)
cedula : TYPE
models.CharField(
max_length=40, db_index=True, unique=True, default=__hash_date__)
telefono : TYPE
models.CharField(max_length=15, blank=True)
"""
if i use vim-pydocstring configured for Numpy Style this is the exit:
""" Persona """
exist any way to add the use the output that generate pydocstring?
Currently {{_return_type_}}
inserts unnesscesary blank line above {{_return_type}}
Please add support for Type Hint (PEP 484) in Python 3.
As of now, pydocstring create the following result.
def foo(n: int ) -> bool:
"""foo
:param n:int)->bool::
"""
return True
It would be much better if we could get following result:
def foo(n: int ) -> bool:
"""foo
:param n (int):
:return (bool):
"""
return True
"""
As we can see below it appear that only the lolipop
is parsed.
def plot_field_along_foil(verts, pred, gt, ylabel="Cp(lolipop)"):
"""plot_field_along_foil.
Args:
lolipop:
Returns:
"""
perhaps related to #57
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.