变量类型注释导致警告

时间:2019-10-29 11:27:37

标签: python annotations pycharm python-3.4

我是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)中提供的信息。

1 个答案:

答案 0 :(得分:0)

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

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