Given:
- A set of computations to calculate interdependent variables
- A set of desired outputs chosen from the variables
I would like to:
- Compute only the variables I need (lazy computation)
- Compute each variable at most once (caching)
- Get rid of the variables that are no longer needed in either the output or the computation of the remaining outputs (garbage collection)
- BONUS: Order the computations so that the biggest variables to be removed can be removed first, in order to reduce memory usage to the max
For example:
a = 1
b = 2
c = b ** 10
d = a + b
In this example:
- If
ais the only required output, thenb,c, anddnever need to be computed - If
canddare required, thenbshould only be calculated once - If
canddare required, thenacan be forgotten as soon asdhas been computed - Since
acan be eventually garbage collected, we try to arrange for that ASAP and therefore computedfirst (or maybe we should start withcif the**operation will temporarily take up more memory? Not completely sure about this...)
When writing the computations as above, as a plain sequence of statements, properties 1 and 4 are not observed.
Meanwhile, it is possible to obtain properties 1 and 3 (missing 2 and 4) using @property:
class DataGetter:
@property
def a(self): return 1
@property
def b(self): return 2
@property
def c(self): return self.b ** 10
@property
def d(self): return self.a + self.b
Likewise, it is possible to obtain properties 1 and 2 (missing 3 and 4) using @cached_property:
class DataGetter:
@cached_property
def a(self): return 1
@cached_property
def b(self): return 2
@cached_property
def c(self): return self.b ** 10
@cached_property
def d(self): return self.a + self.b
Is there a way to ensure all the first 3 properties are met? (And possibly also the 4th?)