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

时间:2013-07-24 02:34:39

标签: python pycharm

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

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

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

def stringify(listOfObjects):
    """
    :type listOfObjects: list
    """
    return ", ".join(map(str, listOfObjects))

我更喜欢的是:

选项1

def stringify(listOfObjects):
    """
    :type listOfObjects: list<Object>  
    """
    return ", ".join(map(str, listOfObjects))

选项2

def stringify(listOfObjects):
    """
    :type listOfObjects: [Object]
    """
    return ", ".join(map(str, listOfObjects))

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

更好的例子

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

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

相关问题 How can I tell PyCharm what type a parameter is expected to be? 请注意,我正在寻找比上述答案更具体的答案。

4 个答案:

答案 0 :(得分:47)

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

#: :type: dict of (str, C)
#: :type: list of str

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

答案 1 :(得分:3)

在python中

type([1,2,3]) == type(['a', 'b', 'c'])

您还可以将字符串添加到整数列表中。

因此,对于您要实现的目标,PyCharm必须神奇地检查您的整个代码,以便在将其作为参数传递之前添加到列表中。

您可以查看此问题Python : define a list of a specific type of object

阵列模块只允许'基本值'。

我能想到的唯一解决方案是创建自己的类,扩展python列表“FoodsList”,可以在添加元素之前检查类型。

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

class FoodsList(list):
    #you can optionally extend append method here to validate type
    pass

def eat(foods):
    """
    :type foods: FoodsList
    """
    energy = 0
    for food in foods:
        energy += food.calories
    return energy


list = FoodsList()
list.append(Food(3))
list.append(Food(4))
print eat(list)

答案 2 :(得分:1)

在以Google格式编写文档字符串时,您可以执行以下操作:

class ToDocument(object):
    """This is my Documentation.

    Args:
        typed_list (:obj:`list` of :obj:`str`): Description of typed list

    """
    ...

当与拿破仑延伸相结合时,这也适用于狮身人面像。有关文档的更多示例,请参阅extension's doc

答案 3 :(得分:0)

https://github.com/undertheseanlp/automatic_speech_recognition中指出, a (旧式,PyCharm docs之前)的方法是使用方括号:

  

list [Foo]:Foo元素列表

     

dict [Foo,Bar]:从Foo到Bar的区域

list of str(如PEP-484中的建议,不起作用在PyCharm中预期。

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

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

from typing import List

"""
Great foo function.

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

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

其他预先声明的类型和更多信息可以在here的Python文档中找到。