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

时间:2019-05-11 06:54:22

标签: python python-3.x pycharm

是否有摆脱警告的方法:

  

未解决的参考'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

2 个答案:

答案 0 :(得分:2)

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

问题在于创建类时,它不存在,因此您的类型注释指向不存在的内容。

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

有关更多信息,请参见PEP 563

答案 1 :(得分:0)

还有一种用于python 3.7之前版本的方法。为避免警告,只需将类型提供为字符串,如下所示:


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

    instance: Union['DeviceManager', None] = None

    @staticmethod
    def get_instance() -> '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!")

来源:https://www.pythonsheets.com/notes/python-future.html