标签: docstring

如何使用 epytext 记录 kwargs 以在 PyCharm 中自动完成提示?

是否可以获得 kwargs 的额外提示,这将为您提供预定义的可能关键字参数的示例?也许epytext不支持它?

class Person():
    def __init__(self, **kwargs):
        """
        @param name: Name
        @type name: str
        @param age: Age
        @type age: int
        @param connections: Connections to other persons
        @type connections: [Person]
        .
        .
        . # I know this is not working
        """
        self.name = kwargs[name] if name in kwargs
        self.age  = kwargs[age] if age in kwargs
        # and so on ...
Run Code Online (Sandbox Code Playgroud)

如果我能在完成提示中得到这样的东西(对不起,我不得不删除图片),那就太好了:

  • > 自我、姓名、年龄、人脉

一个 Quick Doku 看起来像这样:

  • 没有图像*

我真的很喜欢将通用课程作为父母的全球课程。这使得重用更容易。所以这是一个小片段示例:

class common():
    PERSON_DETAILS = dict( name       = ' ',
                           age        = …
Run Code Online (Sandbox Code Playgroud)

python docstring pycharm keyword-argument epytext

6
推荐指数
1
解决办法
2652
查看次数

如何以编程方式访问 DocStrings?

我正在编写一个宏,它采用函数名称,并声明该函数的几个其他版本。我想为这些变体提供与原始方法相同的文档字符串,也许还需要进行一些更改。

为此,我需要检索原始方法的文档字符串。

所以我正在寻找的是一个函数:

get_docstring(functionname::Symbol, argtypes)::String

这样我就可以做到:

julia> s=get_docstring(:values,(Associative,))然后s将被设置为:

s="""
    values(a::Associative)
Return an iterator over all values in a collection.
`collect(values(d))` returns an array of values.
```jldoctest
julia> a = Dict('a'=>2, 'b'=>3)
Dict{Char,Int64} with 2 entries:
  'b' => 3
  'a' => 2
julia> collect(values(a))
2-element Array{Int64,1}:
 3
 2
```
"""
Run Code Online (Sandbox Code Playgroud)

docstring julia

6
推荐指数
1
解决办法
443
查看次数

Python Doctest 中的特殊字符和换行符

我有一个带有如下所示文档字符串的函数,我想测试文档字符串是否正确。我目前正在使用 doctest 模块来执行此操作。但是,我找不到一种方法来表示文档字符串中的新行字符和换行符而不崩溃。这是一个重现该问题的示例:

def foo():
    r"""
    >>> foo() == ['1\n2\n',\
    '3']
    True
    """
    return ['1\n2\n', '3']

import doctest
doctest.testmod()
Run Code Online (Sandbox Code Playgroud)

这会导致错误:

Failed example:
foo() == ['1\n2\n',\
Exception raised:
    Traceback (most recent call last):
      File "C:\Python34\lib\doctest.py", line 1318, in __run
        compileflags, 1), test.globs)
      File "<doctest __main__.foo[0]>", line 1
        foo() == ['1\n2\n',\
                           ^
    SyntaxError: unexpected EOF while parsing
Run Code Online (Sandbox Code Playgroud)

我将如何实现这个目标?

python string docstring special-characters python-3.x

6
推荐指数
1
解决办法
1508
查看次数

Sphinx:链接到 Python 文档字符串中另一个模块中的类的方法

我想在另一个模块(比如说module_2.py)的另一个方法中添加一个指向一个模块(比如说)中的类的方法的链接module_1.py。我希望链接在 Sphinx 中工作。

认为:

模块_1.py

class ABC:
   def foo(self):
      """
      See docstring of module_2.py bar():<link to bar() in module_2.py>
      """
      print("foo")
Run Code Online (Sandbox Code Playgroud)

模块_2.py

class XYZ:
    def bar(self):
    """
    This function prints hello.
    """
    print("hello")
Run Code Online (Sandbox Code Playgroud)

python docstring python-3.x python-sphinx

6
推荐指数
2
解决办法
4919
查看次数

文档字符串中的 python 注释

我发现这个是因为我遇到的一些作业问题是通过文档字符串测试的,它让我失败了。

例如:

def foo(x):
    """
    >>> foo(5)
    25
    >>> foo(6)
    36  # Are you sure?
    """
    return x**2

if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)
Run Code Online (Sandbox Code Playgroud)

上面的示例失败并显示:

Expected:
    36  # are you sure?
Got:
    36
Run Code Online (Sandbox Code Playgroud)

我想知道我们是否不应该在文档字符串中添加注释?或者有没有办法让 python 忽略文档字符串中的注释?

python docstring python-3.x

6
推荐指数
2
解决办法
1272
查看次数

是否有用于 jupyter 笔记本的文档字符串自动完成工具?

我正在寻找一种工具/扩展,可以帮助您在 jupyter notebook 中编写 python 文档字符串。

我通常使用 VS 代码,其中您有自动生成文档字符串模板(例如 sphinx 或 numpy 模板)的autodocstring扩展。在 jupyter notebook 中是否有类似的东西?

我在网上找了很久,一直找不到。

python docstring jupyter-notebook

6
推荐指数
1
解决办法
2062
查看次数

在文档字符串中使用类型别名

是否有typing在文档字符串中使用类型别名或对象的最佳实践?

这个问题可能会吸引基于意见的答案。但也可能是有一个被广泛接受的约定或对特定解决方案的外部工具支持。

相关问题


示例:函数返回一个包含字符串键和值的字典。您会将什么类型放入“退货”部分下的文档字符串中?(我使用的是熊猫风格的文档字符串。)

选项1:只是说它是一个字典。

import typing

strstrdict = typing.Dict[str, str]

def foo() -> strstrdict:
    '''
    bla bla

    Returns
    -------
    dict
        A dictionary with string keys and values that represents ...
    '''
    # code
Run Code Online (Sandbox Code Playgroud)

选项 2:使用类型别名。

import typing

strstrdict = typing.Dict[str, str]

def foo() -> strstrdict:
    '''
    bla bla

    Returns
    -------
    strstrdict
        A dictionary with string keys and values that represents ...
    '''
    # code
Run Code Online (Sandbox Code Playgroud)

选项 3:放入"typing.Dict[str, str]"文档字符串。

import typing

strstrdict …
Run Code Online (Sandbox Code Playgroud)

python docstring typing

6
推荐指数
1
解决办法
439
查看次数

相当于 JavaScript 或 Nodejs 中 Python 的 help()

当我想知道Python中函数的参数数量和参数类型时,我只需使用函数help()来获取它们。但在javascript或nodejs中,很难知道函数的参数类型和参数数量。Javascript 中是否有类似于 Python 帮助的功能,或者是否有其他方式获取该信息?

javascript directory documentation docstring node.js

6
推荐指数
1
解决办法
1223
查看次数

如何记录从元类继承的方法?

考虑以下元类/类定义:

class Meta(type):
    """A python metaclass."""
    def greet_user(cls):
        """Print a friendly greeting identifying the class's name."""
        print(f"Hello, I'm the class '{cls.__name__}'!")

    
class UsesMeta(metaclass=Meta):
    """A class that uses `Meta` as its metaclass."""
Run Code Online (Sandbox Code Playgroud)

我们知道,在元类中定义一个方法意味着它被类继承,并且可以被类使用。这意味着交互式控制台中的以下代码可以正常工作:

class Meta(type):
    """A python metaclass."""
    def greet_user(cls):
        """Print a friendly greeting identifying the class's name."""
        print(f"Hello, I'm the class '{cls.__name__}'!")

    
class UsesMeta(metaclass=Meta):
    """A class that uses `Meta` as its metaclass."""
Run Code Online (Sandbox Code Playgroud)

然而,这种方法的一个主要缺点是我们可能包含在方法定义中的任何文档都丢失了。如果我们help(UsesMeta)在交互式控制台中键入,我们会看到没有对方法的引用greet_user,更不用说我们在方法定义中放入的文档字符串了:

>>> UsesMeta.greet_user()
Hello, I'm the class 'UsesMeta'!
Run Code Online (Sandbox Code Playgroud)

现在当然,__doc__类的属性是 writable …

python docstring metaclass class-method python-3.x

6
推荐指数
1
解决办法
154
查看次数

按名称将函数的文档字符串复制到另一个函数

我希望按名称(使用装饰器)复制同一文件中函数的文档字符串。

我可以轻松地使用当前模块之外的函数来完成此操作,但是当涉及到同一模块(或更具体地说是同一类)时我有点困惑

这是我到目前为止所拥有的:

import inspect

def copy_doc(func_name: str):
    def wrapper(func):
        doc = ... # get doc from function that has the name as func_name
        func.__doc__ = doc
        return func
    retun wrapper
Run Code Online (Sandbox Code Playgroud)

我正在寻找可以完成以下两个示例的东西:

例1:

def this() -> None:
    """Fun doc string"""
    return

@copy_doc('this')
def that() -> None:
    return

print(that.__doc__)
Run Code Online (Sandbox Code Playgroud)

例2:

class This:
    def foo(self) -> None:
        """Fun doc string"""
        return None

    @copy_doc('foo')
    def bar(self) -> None:
        return None

print(This().bar.__doc__)
Run Code Online (Sandbox Code Playgroud)

有什么有趣的想法吗?

python docstring

6
推荐指数
1
解决办法
2921
查看次数