pycharm类型检查器预期的类型dict,改为“无”

Jam*_*ese 6 python typechecking pycharm

在此片段中:

from typing import Dict, Optional 
class T:
    def __init__(self):
        self.bla = {}

    def t(self) -> Dict:
        if self.bla is None:
            self.bla = {'not none': 'nope!'}
        return self.bla
Run Code Online (Sandbox Code Playgroud)

谁能解释为什么intellij / pycharm的类型检查器认为此方法的返回值为None

带有错误消息的代码段

类型检查器似乎只有在我注释t()为be 的返回类型时才感到满意Optional[Dict],但是该方法永远不会返回None,因此我认为它不应该是可选的。

如果我的初始值改变self.bla__init__(){}它仍东西返回值None。如果我使用a str而不是a 则出现相同的错误dict

tsh*_*lif 17

使用以下-> Dict or None注释 pycharm (2019.2) 不会抱怨,我得到了dict类型自动完成fdictnoneres

def fdictnone() -> Dict or None:
    return dict(a=1, b=2)


fdictnoneres = fdictnone()

Run Code Online (Sandbox Code Playgroud)

使用TypeVarpycharm 时,不提供以下dict类型的自动补全tfunres

from typing import TypeVar


T = TypeVar('T', dict, None)


def tfun() -> T:
    return dict(a=1, b=2)


tfunres = tfun()
Run Code Online (Sandbox Code Playgroud)

  • Dict or None,不是你可以做“或”的事情吗!很高兴知道 (2认同)
  • 我不确定为什么当变量可以具有 None 值时,为什么 None 会被区别对待,直到为它分配正确的值为止。 (2认同)

Eli*_* Mi 4

可以但不应该做的是:

class T:
    def __init__(self):
        self.bla = {}

    def t(self) -> dict:
        if self.bla is None:
            result = {'not none': 'nope!'}
            self.bla = result
            return result
        else:
            return self.bla
Run Code Online (Sandbox Code Playgroud)

这样,变量就可以被单独识别。但请注意,这个解决方案很愚蠢——你只是在为我认为 PyCharm 中的错误做一个解决方法!其实我也有同样的问题,但还是没有解决...

现在我建议要么忽略警告,要么通过添加以下内容强制 PyCharm 忽略它:

# noinspection PyTypeChecker
Run Code Online (Sandbox Code Playgroud)

我在某处读到,类型提示在 PyCharm 中尚未完全实现,因此可能仍然会出现......但我不记得在哪里读到过这个,所以不能保证!