导致警告的变量类型注释

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

我是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个回答
0
投票

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

您从哪个模块导入List?我无法在2019.3.3重现该问题。

© www.soinside.com 2019 - 2024. All rights reserved.