Refactoring cached (lazy) property methods in metamodel classes
Many metamodel classes have property methods of this repeating pattern:
def fun(self):
if not hasattr(self, '__prop'):
...
return self.__prop
where __prop
is __value
, __type
or __func
. We can save upto two lines of code per function if we use a decorator function like this:
def cached(func, prop):
def _cached_func(*args, **kwargs):
return getattr(args[0], prop) if hasattr(args[0], prop) else func(*args, **kwargs)
return _cached_func
@cached('__value')
def fun(self):
...
Alternatively use @cached_property
decorator instead of @property
as it is currently. The cached_property is in available in Python >= 3.8 in the functools package.
Edited by Ivan Kondov