PyCharm 抱怨通过另一个模块注入的变量的未解析引用

PyCharm complains about unresolved reference for a variable injected through another module

我有以下文件:

# b.py
from .a import A
class B(A):
    ...

.

# a.py
class A:
    def m(self):
        return B()

.

# __init__.py
from . import a
from .b import B
a.B = B

上面的三个文件在一个名为 p.

的包中

一切正常,除了在模块 a 中,PyCharm 警告 B 是未解析的引用。

问题:

有什么方法可以帮助 PyCharm 了解发生了什么并避免警告?

如果有帮助,我可以重写导入语句,但我想将 AB 类 保留在单独的模块中。

你可以定义 B:

# a.py
def B():
    assert False, "this needs to be overridden"

class A:
    def m(self):
        return B()

您还可以告诉 pycharm 忽略未解析的引用:

# a.py

class A:
    def m(self):
        # noinspection PyUnresolvedReferences
        return B()

我找到了另一种方法来缓解这个问题。将以下假导入添加到 a.py 的末尾:

if __name__ == '__main__':
    from .b import B

这样 PyCharm 就可以停止抱怨,甚至可以检查 B 及其方法。

Of-coarse 导入实际上并未在运行时完成,因为 a.pynot intended to be run as a script