【问题标题】:How to specify that a parameter is a list of specific objects in Python docstrings如何指定参数是 Python 文档字符串中特定对象的列表
【发布时间】:2013-07-23 08:30:36
【问题描述】:

我真的很喜欢在 Python 中使用文档字符串来在项目超出一定大小时指定类型参数。

我无法找到用于指定参数是特定对象列表的标准,例如在 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? 请注意,我正在寻找比上述更具体的答案。

【问题讨论】:

  • 你检查过python网站上的PEP吗?
  • 我没有找到这个,但我可能错过了
  • stackoverflow.com/questions/24853923/… 的可能重复项(我在那里了解到 Python 3.5 的 typing 模块)。

标签: python pycharm


【解决方案1】:

PyCharm's manual 的 cmets 部分有来自开发者的一个很好的提示:

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

它对我很有效。现在它让我想知道在 Python 中记录参数化类的最佳方法是什么:)。

【讨论】:

  • 这个答案现在已经过时了,在 2014 年底创建了PEP 484。但当时这是一个很好的答案! :-)
  • 注意:答案仅对 Python 3.5 及更高版本已过时。
【解决方案2】:

正如PyCharm docs 中指出的那样,a(旧版,PEP-484 之前)这样做的方法是使用方括号:

list[Foo]: Foo 元素列表

dict[Foo, Bar]:从 Foo 到 Bar 的字典

list of str,正如the accepted answer 中所建议的那样,在 PyCharm 中无法正常工作

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

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

from typing import List

"""
Great foo function.

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

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

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

【讨论】:

    【解决方案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)
    

    【讨论】:

    • +1:它以比我希望的更好的方式解决问题 :) 很好的洞察力
    • 虽然我确实怀疑 PyCharm 非常有能力“神奇地”检查我的所有代码以查看我要添加到列表中的内容 - 这就是它的设计目的:)
    【解决方案4】:

    在以 google 风格编写文档字符串时,您可以这样做:

    class ToDocument(object):
        """This is my Documentation.
    
        Args:
            typed_list (:obj:`list` of :obj:`str`): Description of typed list
    
        """
        ...
    

    当与拿破仑扩展结合使用时,这在 sphinx 中也可以很好地工作。有关文档的更多示例,请参阅extension's doc

    【讨论】:

      猜你喜欢
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多