Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: are property fields being cached automatically?

My question is are the following two pieces of code run the same by the interpreter:

class A(object):   def __init__(self):      self.__x = None    @property   def x(self):      if not self.__x:         self.__x = ... #some complicated action      return self.__x 

and the much simpler:

class A(object):   @property   def x(self):       return ... #some complicated action 

I.e., is the interpreter smart enough to cache the property x?

My assumption is that x does not change - finding it is hard, but once you find it once there is no reason to find it again.

like image 596
Guy Avatar asked Jun 21 '11 16:06

Guy


People also ask

Are properties cached Python?

cached_property is a decorator that converts a class method into a property whose value is calculated once and then cached like a regular attribute. The cached value will be available until the object or the instance of the class is destroyed.

Are properties Pythonic?

Properties can be considered the "Pythonic" way of working with attributes because: The syntax used to define properties is very concise and readable.

Does Python cache objects?

Caching is one approach that, when used correctly, makes things much faster while decreasing the load on computing resources. Python's functools module comes with the @lru_cache decorator, which gives you the ability to cache the result of your functions using the Least Recently Used (LRU) strategy.

Does Python cache results?

Memoization allows you to optimize a Python function by caching its output based on the parameters you supply to it. Once you memoize a function, it will only compute its output once for each set of parameters you call it with. Every call after the first will be quickly retrieved from a cache.

What is @cached_property in Python?

Python Functools – cached_property () The @cached_property is a decorator which transforms a method of a class into a property whose value is computed only once and then cached as a normal attribute. Therefore, the cached result will be available as long as the instance will persist and we can use that method as an attribute of a class i.e.

How long the cached result will be available in Python?

Therefore, the cached result will be available as long as the instance will persist and we can use that method as an attribute of a class i.e cached_property is a part of functools module in Python.

How do I create a cache in Python?

We can create local data structures in our Python processes to build the cache or host the cache as a server that acts as a proxy and serves the requests. There are built-in Python tools such as using cached_property decorator from functools library.

What is the property() function in Python?

Python’s property () is the Pythonic way to avoid formal getter and setter methods in your code. This function allows you to turn class attributes into properties or managed attributes. Since property () is a built-in function, you can use it without importing anything. Additionally, property () was implemented in C to ensure optimal performance.


2 Answers

No, the getter will be called every time you access the property.

like image 138
Sven Marnach Avatar answered Sep 22 '22 05:09

Sven Marnach


No you need to add a memoize decorator:

class memoized(object):    """Decorator that caches a function's return value each time it is called.    If called later with the same arguments, the cached value is returned, and    not re-evaluated.    """    def __init__(self, func):       self.func = func       self.cache = {}    def __call__(self, *args):       try:          return self.cache[args]       except KeyError:          value = self.func(*args)          self.cache[args] = value          return value       except TypeError:          # uncachable -- for instance, passing a list as an argument.          # Better to not cache than to blow up entirely.          return self.func(*args)    def __repr__(self):       """Return the function's docstring."""       return self.func.__doc__    def __get__(self, obj, objtype):       """Support instance methods."""       return functools.partial(self.__call__, obj)  @memoized def fibonacci(n):    "Return the nth fibonacci number."    if n in (0, 1):       return n    return fibonacci(n-1) + fibonacci(n-2)  print fibonacci(12) 
like image 21
fabrizioM Avatar answered Sep 22 '22 05:09

fabrizioM