python - 带有单例类型提示的未解析引用

标签 python python-3.x pycharm

<分区>

有没有办法消除警告:

Unresolved reference 'DeviceManager' ...

对于这种单例模式?

class DeviceManager:
    """ Holds all devices and manages their distributed use. """

    instance: Union[DeviceManager, None] = None  # warning Unresolved reference 'DeviceManager'

    @staticmethod
    def get_instance() -> DeviceManager:  # warning Unresolved reference 'DeviceManager'
        """ Singleton instance. """

        if DeviceManager.instance is None:
            DeviceManager()

        return cast(DeviceManager, DeviceManager.instance)

    def __init__(self) -> None:
        """ Create instance. """
        if DeviceManager.instance is None:
            DeviceManager.instance = self
        else:
            raise Exception("This class is a singleton!")

截图:

Screenshot PyCharm version 2019.1

最佳答案

是的,如果您使用的是 Python >= 3.7。

问题是在创建类时,它并不存在,因此您的类型注释指向不存在的东西。

要解决此问题,您可以使用 from __future__ import annotations,这会将此类注释的评估推迟到创建类之后。

参见 PEP 563获取更多信息。

关于python - 带有单例类型提示的未解析引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56087950/

相关文章:

python - 创建受密码保护的 zip 文件?

python - 根据值(理解)对嵌套字典中的元素进行计数

version-control - PyCharm 中用于 Jupyter 笔记本的 VCS

Python 输入 : declare type of callable when give it instance method

python - imp 模块已弃用

python - 如何在python中读取Mat v7.3文件?

python - 从URL中获取ID并从数据库中选择它

python - 如何将矩阵顺时针旋转 90 度?

python - Python 中的 XGBoost XGBClassifier 默认值

python - 如何禁用 pytest.ini 中的多个插件?