【问题标题】:Variable type annotations leading to warnings导致警告的变量类型注释
【发布时间】:2020-02-24 15:25:10
【问题描述】:

我是 Python 开发的新手,正在尝试解决问题。我正在使用 Pycharm 进行开发。我目前正在尝试注释变量的类型,以便通过自动完成和建议更轻松地访问。我尝试了代码的迭代,结果好坏参半。

这是有问题的代码:

path = os.path.dirname(os.path.realpath(__file__))  # type: str
components = path.split(os.sep)  # type: list[str]

显示的第一个问题是在第二行类型注释的左大括号处。它说:

Class 'type' does not define '__getitem__', so the '[]' operator cannot be used on its instances.

我搜索了一下,虽然问题似乎很清楚,但打开 list 类的代码清楚地显示了一个方法 __getitem__

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """

....

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

好的,也许这并不容易理解,并且还有其他一些加载机制在起作用。此外,“问题”似乎是我使用了list[str] 而不是List[str]。所以我修改了代码:

path = os.path.dirname(os.path.realpath(__file__))  # type: str
components = path.split(os.sep)  # type: List[str]

现在一切都崩溃了:第二行现在抱怨这个:

Expected type 'List[str]', got 'List[str]' instead`

之前关于__getitem__ 的问题仍然存在。

有没有办法在不给检查器造成问题的情况下注释这些变量?在这方面,我对 Python 文档不太满意,没有明确说明其内置方法的返回类型。我必须依赖 Pycharm 在文档弹出窗口中提供的信息 (Ctrl+q)。

【问题讨论】:

    标签: python annotations pycharm python-3.4


    【解决方案1】:

    使用List[str] 代替list[str] 是一个正确的解决方案,因为内置类型不能用于类型提示,相应的PEP 尚未被接受。

    你从哪个模块导入List?我无法重现 2019.3 中的问题。

    【讨论】:

    • Pycharm 建议_ast.List(expr),我就是这么用的。
    • 请切换到typing.List
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2012-05-07
    相关资源
    最近更新 更多