如何指定参数是 Python 文档字符串中特定对象的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17824280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to specify that a parameter is a list of specific objects in Python docstrings
提问by Alex
I really like using docstrings in Python to specify type parameters when projects get beyond a certain size.
当项目超过特定大小时,我非常喜欢在 Python 中使用文档字符串来指定类型参数。
I'm having trouble finding a standard to use to specify that a parameter is a list of specific objects, e.g. in Haskell types I'd use [String] or [A].
我无法找到用于指定参数是特定对象列表的标准,例如在 Haskell 类型中我会使用 [String] 或 [A]。
Current standard (recognisable by PyCharm editor):
当前标准(可被 PyCharm 编辑器识别):
def stringify(listOfObjects):
"""
:type listOfObjects: list
"""
return ", ".join(map(str, listOfObjects))
What I'd prefer:
我更喜欢:
OPTION 1
选项1
def stringify(listOfObjects):
"""
:type listOfObjects: list<Object>
"""
return ", ".join(map(str, listOfObjects))
OPTION 2
选项 2
def stringify(listOfObjects):
"""
:type listOfObjects: [Object]
"""
return ", ".join(map(str, listOfObjects))
I suppose that wasn't a great example - the more relevant use case would be one where the objects in the list must be of a specific type.
我想这不是一个很好的例子 - 更相关的用例是列表中的对象必须是特定类型的用例。
BETTER EXAMPLE
更好的例子
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
So, other than the fact that I'm getting hungry, this example illustrates that if called with a list of the wrong kind of object, the code would break. Hence the importance of documenting not only that it needs a list, but that it needs a list of Food.
所以,除了我越来越饿的事实之外,这个例子说明如果用错误类型的对象列表调用,代码会中断。因此,记录的重要性不仅在于它需要一份清单,而且还需要一份食品清单。
RELATED QUESTIONHow can I tell PyCharm what type a parameter is expected to be?Please note that I'm looking for a more specific answer than the one above.
相关问题如何告诉 PyCharm 参数应该是什么类型?请注意,我正在寻找比上述更具体的答案。
采纳答案by Michael Korbakov
In comments section of PyCharm's manualthere's a nice hint from developer:
在PyCharm 手册的评论部分,开发人员有一个很好的提示:
#: :type: dict of (str, C)
#: :type: list of str
It works for me pretty well. Now it makes me wonder what's the best way to document parametrized classes in Python :).
它对我很有效。现在让我想知道在 Python 中记录参数化类的最佳方法是什么 :)。
回答by fsw
in python
在蟒蛇
type([1,2,3]) == type(['a', 'b', 'c'])
you can also add a string to list of ints.
您还可以将字符串添加到整数列表。
So for what you are trying to achieve PyCharm would have to magically check your whole code for what you are adding to the list before passing it as argument.
因此,对于您要实现的目标,PyCharm 必须在将其作为参数传递之前神奇地检查整个代码中是否添加到列表中。
You can take a look at this question Python : define a list of a specific type of object
你可以看看这个问题Python :define a list of a specific type of object
Array module however allows only 'basic values'.
然而,数组模块只允许“基本值”。
Only solution i can think of here is to create your own class that extends python list "FoodsList" that can check for type before adding element.
我在这里能想到的唯一解决方案是创建您自己的类,该类扩展了可以在添加元素之前检查类型的 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)
回答by Kim
When writing docstrings in the google style you can do:
以 google 风格编写文档字符串时,您可以执行以下操作:
class ToDocument(object):
"""This is my Documentation.
Args:
typed_list (:obj:`list` of :obj:`str`): Description of typed list
"""
...
This also works pretty fine in sphinx, when combined with the napoleon-extension. Refer to the extension's docfor more examples on documentation.
回答by Hendrik
As pointed out in the PyCharm docs, a(legacy, pre-PEP-484) way of doing this is using square brackets:
正如PyCharm 文档中所指出的,一种(传统的,PEP-484 之前的)方法是使用方括号:
list[Foo]: List of Foo elements
dict[Foo, Bar]: Dict from Foo to Bar
list[Foo]: Foo 元素列表
dict[Foo, Bar]: 从 Foo 到 Bar
list of str
, as suggested in the accepted answer, does not workas expected in PyCharm.
list of str
,如建议接受的答案, 不工作按预期在PyCharm。
Starting with Python 3.5 and the implementation of PEP-484, you can also use type hints, which may be nicely supported by your IDE/editor. How this is easily done in PyCharm is explained here.
从 Python 3.5 和PEP-484的实现开始,您还可以使用类型提示,您的 IDE/编辑器可能会很好地支持它。此处解释了如何在 PyCharm 中轻松完成此操作。
In essence, to declare a list return type using type-hinting (Python >=3.5), you may do something like this:
本质上,要使用类型提示(Python >=3.5)声明列表返回类型,您可以执行以下操作:
from typing import List
"""
Great foo function.
:rtype: list[str]
"""
def foo() -> List[str]:
return ['some string', 'some other string']
Here we declare (somewhat redundantly) that the function foo
returns a list of strings, both in the type hint -> List[str]
and in the docstring :rtype: list[str]
.
在这里,我们声明(有点多余)该函数foo
在类型提示-> List[str]
和 docstring 中返回一个字符串列表:rtype: list[str]
。
Other pre-declared types and more info can be found in the Python docs for typing.
其他预先声明的类型和详细信息可以在Python文档的找到打字。