I have multiple functions that make use of a single variable, the computation of this variable is costly, and so I would not like to repeat this. I have two simple proposed methods for doing this, and was wondering which you feel is more "pythonic" or a better method.
class A:
def __init__(self):
self.hasAttr = False
def compute_attr(self):
self.attr = 10
self.hasAttr = True #for func2 only
def func1(self):
try:
print self.attr == 10
except AttributeError:
self.compute_attr()
self.func1()
def func2(self):
if not self.hasAttr: self.compute_attr()
print self.attr == 10
a = A()
a.func1()
a.func2()
func1 uses a simple try except to catch the AttributeError and compute the attribute in this case. func2 uses a stored boolean to check if the computation has been completed or not.
Is there any reason as to one method would be preferred over another? Furthermore, would there be any point in defining a decorator that does the check as in func2?
Thanks for any help.