【问题标题】:Unresolved reference with singleton type hinting [duplicate]带有单例类型提示的未解决引用[重复]
【发布时间】:2019-09-28 23:22:33
【问题描述】:

有没有办法摆脱警告:

未解析的引用'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!")

截图:

【问题讨论】:

  • 你可能想看看Creating a singleton in Python 了解更多创建单例的pythonic方法
  • 好的,可能有更好的方法来编写单例,但上面链接提供的示例不使用类型提示。据我所知,它们都会遇到返回类型未解析或它们的类型是任何或对象的相同问题,这不是解决方案。 get_instance 返回类的类型很重要。

标签: python python-3.x pycharm


【解决方案1】:

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

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

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

更多信息请参见PEP 563

【讨论】:

  • 非常感谢,我用的是3.6.7版本,改成3.7.3解决了这个问题。我还必须删除会再次显示警告的 PyCharms 向后兼容性功能,但 PyCharm 会显示引导参数的信息。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 2020-10-27
    • 2020-01-26
    • 2017-08-18
    • 2020-07-24
    • 2018-08-24
    • 1970-01-01
    相关资源
    最近更新 更多