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
The decorator from Denis Otkidach mentioned in @unutbu's answer was published in O'Reilly's Python Cookbook. Unfortunately O'Reilly doesn't specify any license for code examples – just as informal permission to reuse the code.
If you need a cached property decorator with a liberal license, you can use Ken Seehof's @cached_property
from ActiveState code recipes. It's explicitly published under the MIT license.
def cached_property(f):
"""returns a cached property that is calculated by function f"""
def get(self):
try:
return self._property_cache[f]
except AttributeError:
self._property_cache = {}
x = self._property_cache[f] = f(self)
return x
except KeyError:
x = self._property_cache[f] = f(self)
return x
return property(get)
No, the getter will be called every time you access the property.