如何指定参数是Python文档字符串中特定对象的列表

Ale*_*lex 43 python pycharm

我非常喜欢在Python中使用docstrings来指定项目超出一定大小时的类型参数.

我找不到用于指定参数是特定对象列表的标准,例如在Haskell类型中我使用[String]或[A].

当前标准(PyCharm编辑可识别):

def stringify(listOfObjects):
    """
    :type listOfObjects: list
    """
    return ", ".join(map(str, listOfObjects))
Run Code Online (Sandbox Code Playgroud)

我更喜欢的是什么:

选项1

def stringify(listOfObjects):
    """
    :type listOfObjects: list<Object>  
    """
    return ", ".join(map(str, listOfObjects))
Run Code Online (Sandbox Code Playgroud)

方案2

def stringify(listOfObjects):
    """
    :type listOfObjects: [Object]
    """
    return ", ".join(map(str, listOfObjects))
Run Code Online (Sandbox Code Playgroud)

我想这不是一个很好的例子 - 更相关的用例是列表中的对象必须是特定类型的用例.

更好的例子

class Food(Object):
    def __init__(self, calories):
        self.calories = calories

class Apple(Food):
    def __init__(self):
        super(self, 200)

class Person(Object):
    energy = 0
    def eat(foods):
        """
        :type foods: [Food]  # is NOT recognised by editor
        """
        for food in foods:
            energy += food.calories
Run Code Online (Sandbox Code Playgroud)

所以,除了我饿了之外,这个例子说明如果使用错误类型的对象列表调用,代码就会破坏.因此,记录它不仅需要一个清单,而且需要一份食物清单的重要性.

相关问题 如何告诉PyCharm参数的类型是什么? 请注意,我正在寻找比上面更具体的答案.

Mic*_*kov 50

PyCharm手册的评论部分,开发人员提供了一个很好的提示:

#: :type: dict of (str, C)
#: :type: list of str
Run Code Online (Sandbox Code Playgroud)

它非常适合我.现在它让我想知道在Python中记录参数化类的最佳方法是什么:).

  • 注意:答案仅适用于Python 3.5及更高版本. (7认同)

hen*_*rik 11

正如PyCharm 文档中所指出的,一种(传统的,PEP-484 之前的)方法是使用方括号:

list[Foo]: Foo 元素列表

dict[Foo, Bar]: 从 Foo 到 Bar

list of str,如已接受的答案所建议不起作用按预期在PyCharm。

从 Python 3.5 和PEP-484的实现开始,您还可以使用类型提示,您的 IDE/编辑器可能会很好地支持它。此处解释如何在 PyCharm 中轻松完成此操作

本质上,要使用类型提示(Python >=3.5)声明列表返回类型,您可以执行以下操作:

from typing import List

"""
Great foo function.

:rtype: list[str]
"""
def foo() -> List[str]:
    return ['some string', 'some other string']
Run Code Online (Sandbox Code Playgroud)

在这里我们声明(有点多余)该函数foo返回一个字符串列表,在类型提示-> List[str]和文档字符串中:rtype: list[str]

其他预先声明的类型和详细信息可以在Python文档的找到打字