【问题标题】:How can I get PyCharm to recognize a custom property decorator?如何让 PyC​​harm 识别自定义属性装饰器?
【发布时间】:2019-03-20 21:24:44
【问题描述】:

让我们考虑以下示例类:

class Foo:
    def __init__(self):
        self._bar = None

    @property
    def bar(self):
        if self._bar is None:
            self._bar = ...  # a long computation
        return self._bar

我创建了一个cachedproperty 装饰器来隐式处理将计算结果存储为类实例的成员。这是此类装饰器类的简化示例:

class cachedproperty(property):
    def __init__(self, fget):
        @functools.wraps(fget)
        def cfget(obj):
            name = '_' + fget.__name__
            if not hasattr(obj, name):
                setattr(obj, name, fget(obj))
            return getattr(obj, name)
        super().__init__(cfget)

现在Foo 类看起来像这样:

class Foo:
    @cachedproperty
    def bar(self):
        return ...  # a long computation

尽管它有效,但 PyCharm 现在无法将bar 视为Foo 的属性,而是将其视为一种方法,这有点不方便。例如,可以在自动完成下拉菜单中看到这一点:

我的问题是:如何强制 PyCharm 将我的自定义属性装饰器视为实际属性?

【问题讨论】:

    标签: python python-3.x properties pycharm python-decorators


    【解决方案1】:

    看起来 PyCharm 完全根据装饰器的名称做出这个决定。例如,将您的 cachedproperty 装饰器重命名为 cached_property(使其与该名称的 Django's decorator 匹配)有效:

    ...而使用具有不同名称的内置 property 装饰器不会:

    【讨论】:

    • 这很不幸,因为我的代码中有几个自定义的“属性”装饰器,我希望能够为 PyCharm 相应地“标记”它们
    猜你喜欢
    • 2021-01-29
    • 2013-09-26
    • 2016-09-17
    • 1970-01-01
    • 2015-12-16
    • 2021-05-17
    • 2018-07-20
    • 2016-08-28
    • 1970-01-01
    相关资源
    最近更新 更多