繁体   English   中英

如何注解arguments使列表成员属于同一类型?

[英]How to annotate arguments so that list members are of the same type?

我想将相同数据类型的成员列表传递给 function。为了检查列表是否包含相同类型的成员,我使用了一个输入模块。 但是 IDE 只有在列表中没有某种类型的成员时才会警告我,如果至少有一个成员属于某种类型则不会警告我。 如果列表中的至少一个成员与所需类型不匹配,如何使 IDE 发出警告? 我被迫使用 Python 2.7 和 PyCharm IDE。

from typing import List


def f(a,  # type: List[int]
      ):
    return a


f([""])  # Pycharm warnning: Expected type'List[int]', got 'List[str]' instead
f([1, ""])  # Pycharm do not warnning

我在文档中读到要注释 arguments 最好使用抽象集合类型,例如Sequence 我尝试了Sequence[int] ,但结果与List[int]相同。 使用Tuple[int]一切都如我所料,可能是因为“元组”是不可变的,但我的 function 恰好需要list

对于List的库typing导入,我认为注释a: List[int]不能帮助您检查您的列表是否为 integer。当运行 python 时,它将被忽略。

但是,如果要使用 List[int] 注释来确定,则可以使用mypy库进行类型检查。

作为不使用mypy的替代方法,我创建了以下代码供您参考:

def f(a):
    '''Checking the type of objects in list

    for statement will help to check the type
    of each object in the list and "list_is_int"
    will update the status
    '''

    for x in a:
        if type(x) is int:
            list_is_int = True
        elif type(x) is not int:
            list_is_int = False
        
    if list_is_int == True: 
        print("The list is all integer")
    else:
        print("# Pycharm warnning: Expected type'List[int]', got 'List[str]' instead")

f([1,2,3])  # Will output: The list is all integer
f(["1", "2", "3"])  # Pycharm warnning: Expected type'List[int]', got 'List[str]' instead

您可以更改第 18 行print("# Pycharm warnning: Expected type'List[int]', got 'List[str]' instead")raise TypeError("Only integer allowed")

看看它做了什么,祝你好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM