I have a set of arrays that are very large and expensive to compute, and not all of my code will necessarily need it at any start. I would like to make their declaration optional, but ideally without having to rewrite all the code.
An example of how this is done:
x = function_that_generates_huge_array_slowly(0) y = function_that_generates_huge_array_slowly(1)
An example of what I would like to do:
x = lambda: function_that_generates_huge_array_slowly(0) y = lambda: function_that_generates_huge_array_slowly(1) z = x * 5
When using lambda, as indicated above, one of the desired effects is achieved - the calculation of the array is delayed until it is needed. If you use the variable "x" more than once, it needs to be calculated every time. I would like to calculate it only once.
EDIT: After some additional searching, it seems like you can do what I want (approximately) with the βlazyβ attributes in the class (like http://code.activestate.com/recipes/131495-lazy-attributes/ ). I donβt think there is a way to do something like this without making a separate class?
EDIT2: I'm trying to implement some of the solutions, but I ran into a problem because I don't understand the difference between:
class sample(object): def __init__(self): class one(object): def __get__(self, obj, type=None): print "computing ..." obj.one = 1 return 1 self.one = one()
and
class sample(object): class one(object): def __get__(self, obj, type=None): print "computing ... " obj.one = 1 return 1 one = one()
I think that some changes in them are what I am looking for, since expensive variables are meant to be part of the class.