标签: docstring

我可以使用VIM在Python中查看函数的doc字符串吗?

在VIM中编写Python时有没有办法查看函数的doc字符串?

例如:

def MyFunction(spam):
    """A function that foobars the spam
    returns eggs"""

    return foobar(spam).eggs()
Run Code Online (Sandbox Code Playgroud)

我希望能够键入MyFunction(spam0)并查看文档字符串,作为工具提示或状态栏或VIM允许的任何其他方式.

python vim docstring

8
推荐指数
1
解决办法
2331
查看次数

如何创建仅在__init__中声明的Python/Sphinx文档对象属性?

我有带有对象属性的Python类,它们只被声明为运行构造函数的一部分,如下所示:

class Foo(object):
    def __init__(self, base):
        self.basepath = base

        temp = []
        for run in os.listdir(self.basepath):
            if self.foo(run):
                temp.append(run)
        self.availableruns = tuple(sorted(temp))
Run Code Online (Sandbox Code Playgroud)

如果我现在使用help(Foo)或尝试Foo在Sphinx中记录,则不显示self.basepathself.availableruns属性.这对我们API的用户来说是一个问题.

我已经尝试寻找一种标准方法来确保解析器可以找到这些"动态声明"的属性(最好是docstring'd),但到目前为止还没有运气.有什么建议?谢谢.

python documentation attributes docstring python-sphinx

8
推荐指数
2
解决办法
7184
查看次数

如何为Sphinx的Python文档字符串中的变量指定类型?

您可以在Python文档字符串中指定参数类型,如下所示:

def __init__(self, canvas, segments):
    """Class constructor.

    :param canvas: the PDF canvas object
    :param segment: The layer segments to be drawn.

    :type canvas: `canvas.Canvas`
    :type segments: list of str
    """
    ...
Run Code Online (Sandbox Code Playgroud)

使用Sphinx的autodoc功能,可以生成参数列表,并且每个参数都可以使用其类型进行正确标记.

但是如何使用实例属性执行此操作?像这样的东西

class Path(object):
    """
    :ivar edge_indices: The indices within `textured_points` of the places.

    :type edge_indices: list of int
    """
Run Code Online (Sandbox Code Playgroud)

不起作用.人们可以在单词之后加上单词类型,:ivar但在这里,它由三个单词组成,因此不起作用.

python docstring python-sphinx autodoc

8
推荐指数
1
解决办法
1278
查看次数

告诉PyCharm代码生成的类字段

作为一个最小的案例,我有一个Example类似于一系列其他类的抽象容量.

class Example(object):
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)            

class Test(Example):
    def __init__(self, foo='bar'):
        super(Test, self).__init__(foo=foo)
Run Code Online (Sandbox Code Playgroud)

在实际情况下,Example做更多的事情.

有没有办法Test通知PyCharm Test将有一个字段Test.foo甚至更好,让它知道foo预计会是一个字符串?

需要明确的是,请考虑将字段设置委托ExampleTest不可能.

我得到的最接近的@ivar是Epydoc,但我无法让它发挥作用

python docstring pycharm python-2.7

8
推荐指数
2
解决办法
997
查看次数

Clojure:如何获取函数docstring?

我试图获得Clojure中函数的文档字符串,但是我遇到了几个问题,因为我找到的所有函数实际上都打印了函数签名+ docstring.

因此,例如,(doc map)实际上将打印类似的东西.


clojure.core /图

([f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3&colls])

返回一个惰性序列,包含将f应用于...的结果

我只对让docstring不打印它,也没有它的名称空间或arity感兴趣.我正在寻找的东西 (get-doc function-name)会返回一个字符串

"返回一个由将f应用于...的结果组成的惰性序列."

在Clojure中这可能吗?

docstring clojure

8
推荐指数
1
解决办法
1380
查看次数

make函数在help()函数中有参数的省略号

如果键入help(vars),将生成以下内容:

vars(...)
    vars([object]) -> dictionary

    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.
Run Code Online (Sandbox Code Playgroud)

当我执行以下操作时:

def func(x, y): pass

help(func)
Run Code Online (Sandbox Code Playgroud)

它显示了这个:

func(x, y)
Run Code Online (Sandbox Code Playgroud)

如何更改它以便它显示...在括号之间,如内置函数vars()?(也就是说func(...))

编辑:有人建议使用docstring,但这不会做我想要的.这是一个例子:

def func(x, y):
    """func(...) -> None"""

help(func)
Run Code Online (Sandbox Code Playgroud)

结果:

func(x, y)
    func(...) -> None
Run Code Online (Sandbox Code Playgroud)

你看,x, y仍在显示而不是...

python docstring

8
推荐指数
1
解决办法
734
查看次数

在 Visual Studio Code Debugger 中 Pytesting Doctests

假设我有以下代码foo.py

def start():
    """
    >>> start()
    Hello world
    """
    test = 10
    print('Hello world')
Run Code Online (Sandbox Code Playgroud)

通常,我会通过pytest foo.py --doctest-modules -v在终端中运行来运行 doctest 。相反,我希望能够通过 Visual Studio Code 的内置调试器对其进行测试,以跟踪变量和调用堆栈。

我的项目中有以下配置launch.json

"name": "PyTest",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "${config:python.pythonPath}",
"module": "pytest",
"args": [
    "${file}",
    "--doctest-modules",
    "-v"
],
"cwd": "${workspaceRoot}",
"env": {},
"envFile": "${workspaceRoot}/.env",
"debugOptions": [
    "RedirectOutput"
]
Run Code Online (Sandbox Code Playgroud)

但是,当我打开文件并在 VSCode 调试器中运行 PyTest 调试配置时,doctests 仅在内置终端中运行 - 调试器面板中没有显示任何内容。我应该如何配置调试器才能使用它的变量和调用堆栈?

python doctest docstring pytest visual-studio-code

8
推荐指数
1
解决办法
2040
查看次数

你是否应该总是记录函数,即使是多余的(特别是 python)?

我尝试使用活动和描述性的函数名称,然后我用活动和描述性文本 (!) 记录这些名称。这会生成看起来多余的代码。

python中的简化(但不是那么不切实际)示例,遵循numpy docstring样式:

def calculate_inverse(matrix):
    """Calculate the inverse of a matrix.

    Parameters
    ----------
    matrix : ndarray
        The matrix to be inverted.

    Returns
    -------
    matrix_inv : ndarray
        The inverse of the matrix.

    """
    matrix_inv = scipy.linalg.inv(matrix)
    return matrix_inv
Run Code Online (Sandbox Code Playgroud)

特别是对于 python,我已经阅读了PEP-257和 sphinx/napoleon 示例numpy和 Google 风格的文档字符串。我喜欢我可以为我的函数自动生成文档,但是对于像上面这样的冗余示例,“最佳实践”是什么?是否应该简单地不记录“明显”的类、函数等?“显而易见”的程度当然变得主观......

我想到了开源的分布式代码。多个作者建议代码本身应该是可读的(calculate_inverse(A)比 更好dgetri(A)),但多个最终用户将从 sphinx 样式的文档中受益。

docstring python-sphinx numpydoc sphinx-napoleon

7
推荐指数
2
解决办法
1387
查看次数

如何在python docstring中指定不同的返回类型

我目前正在使用Sphinx和autodoc插件为我的python包编写文档.对于函数返回值,我可以写例如:returns: int: count,告诉sphinx存在类型为int的返回值,命名为count.

我现在有一个函数,它让我的数据库中的项目的前辈:

def get_previous_release(release_id):
    """ Holt Vorgängeritem eines Items mit der ID release_id

        :param release_id: ID des items für das Release
        :type release_id: int

    """

    if not isinstance(release_id, int):
        raise ValueError('get_previous_release expects an Integer value for the parameter release_id')

    try:
        release = my_queries.core.get_by_id(release_id)
    except IndexError:
        raise LookupError('The item with id {} could no be found'.format(release_id))

    if 'Alpha-Release' in release.name:
        release = AlphaRelease(release.key, release.name, release.state)
    elif 'Beta-Release' in release.name:
        release = BetaRelease(release.key, release.name, release.state)
    elif '-Release' in …
Run Code Online (Sandbox Code Playgroud)

python docstring python-sphinx

7
推荐指数
1
解决办法
7190
查看次数

Python Sphinx:如何将代码嵌入到文档字符串中?

如何将代码嵌入到文档字符串中,以告诉 Sphinx 将代码格式化为与 Markdown 中类似的格式(不同的背景颜色、等宽无字体)?例如记录代码使用示例。

""" This is a module documentation

Use this module like this:

   res = aFunction(something, goes, in)
   print(res.avalue)

"""
Run Code Online (Sandbox Code Playgroud)

python docstring python-3.x python-sphinx

7
推荐指数
1
解决办法
7916
查看次数