【问题标题】:How to have a decorator return a (cached) property iff it was previously None?如果以前没有,如何让装饰器返回(缓存的)属性?
【发布时间】:2015-05-11 18:50:20
【问题描述】:

在一个参数是可选的并且可以计算的类中,我通常有类似的东西

class Demo(object):
    def __init__(self, value=None):
        self._value = value

    @property
    def value(self):
        if self._value is None:
            # some calculations to get value
            self._value = value
        return self._value

恕我直言,这非常嘈杂,类似于记忆前言。我更喜欢类似的东西

    @property_if_None
    def value(self):
        # some calculations to get value
        return value

如果value 不是可选的,只是没有设置我会使用@functools.lru_cached,但这不起作用。


当然我可以简单地将__init__ 更改为

    def __init__(self, value=None):
        if value is None:
            # some calculations to get value
        self.value = value

但是让我们假设# some calculations to get value 很长并且应该在它自己的函数中——我更愿意称之为value() 从而有效地使value 成为@property,但当且仅当它没有设置为一个值≠None...

【问题讨论】:

    标签: python caching decorator nonetype


    【解决方案1】:

    可能不是最完美的解决方案,但这是我的目标:

    import functools
    
    # http://stackoverflow.com/a/28961925/321973
    def property_if_None_generator(f, cached=False):
        @functools.wraps(f)
        def wrapped(self):
            value = self.__getattribute__('_' + f.__name__)
            if value is not None:
                return value
            else:
                return f(self)
        if cached:
            wrapped = functools.lru_cache()(wrapped)
        return property(wrapped)
    
    property_if_None = lambda f: property_if_None_generator(f, cached=False)
    cached_property_if_None = lambda f: property_if_None_generator(f, cached=True)
    

    那么问题的例子就会变成

    class Demo(object):
        def __init__(self, value=None):
            self._value = value
    
        @chached_property_if_None
        def value(self):
            # some calculations to get value
            return value
    

    【讨论】:

    • 我相信您的 Demo 课程,它需要设置并返回 self._value 才能实际工作。
    • @martineau 你能更具体一点吗?它设置为可选的构造函数参数(或 None,如果未提供),但它当然不需要返回 - @cached_property_if_None 装饰器是由 @functools.lru_cache() 包装的 @property_if_None,它采用返回的 @987654329 @ 并缓存它。
    • 太棒了。没有评论的反对票。现在那帮助我改进...任何实际反馈将不胜感激,我也在codereview.SE上发布了这段代码..
    猜你喜欢
    • 2020-05-12
    • 2020-06-01
    • 1970-01-01
    • 2018-11-26
    • 2019-03-20
    • 2013-08-23
    • 2021-07-19
    • 2014-10-02
    相关资源
    最近更新 更多