如何在Python上注释空列表[重复]

问题描述 投票:0回答:1

我不知道通过输入 module 来注释空数组。

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

就像

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

它工作得很好,但我猜它不适合通过输入 module 进行 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

是否收费?如果这是错误的,我想知道如何将空数组对象注释为参数。

python typing
1个回答
2
投票

首先不要在方法之外定义列表..否则你的方法会对多次调用产生副作用。

其次,如果您要使用该变量,请不要将其称为

_
。按照惯例,该名称用于您永远不会使用的类型。

关于实际类型提示!如果您创建一个空列表,则类型推断不够智能,无法猜测它最终将用于什么用途。这意味着它默认为

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
© www.soinside.com 2019 - 2024. All rights reserved.