如何在python上注释空列表

时间:2019-06-28 05:36:00

标签: python typing

通过键入模块,我不知道空数组的注释。

有时候,我使用列表作为数据容器。

就像

box = []

def fuga(box):
    ```box is container of processed data in this function```
    for _ in range(10):
        res = hoge(_) # API response 
        box.append(res) 
    return box

到目前为止,我编写的代码如下,

from typing import List

box = []

def fuga(box: list) -> List[str]: 
    for _ in range(10):
        res: str = hoge(_)
        box.append(res)
    return box

它很好用,但是我猜不是通过键入模块进行python编码。这是因为开发人员很难理解变量“ box”具有哪些对象。因此,我认为适当的注释是

from typing import List 

box = []

def fuga(box: List[None]) -> List[str]: 
    for _ in range(10):
        res: str = hoge(_)
        box.append(res)
    return box

它是否收集?而且如果错误,我想知道如何注释空数组对象作为参数。

1 个答案:

答案 0 :(得分:1)

首先不要在方法外部定义列表。否则,您的方法将对多个调用产生副作用。

第二,如果要使用该变量,请不要将其命名为_。按照惯例,该名称用于您永远不会使用的类型。

转到实际的类型提示!如果创建一个空列表,则类型推断还不够聪明,无法猜测其最终用途。这意味着它默认为List[Any]。而是明确声明它:

def fuga() -> List[str]: 
    box: List[str] = []
    for i in range(10):
        res: str = hoge(i)
        box.append(res)
    return box

在上面的示例中,我从参数中删除了box。如果您确实希望将其传递,则应重命名它。就目前而言,这将掩盖全局变量,这是一种不好的做法。尝试这样的事情:

box: List[str] = []

def fuga(input_box: List[str]) -> List[str]: 
    for i in range(10):
        res: str = hoge(i)
        input_box.append(res)
    return input_box