I’m writing an application that collects and displays the data from a scientific instrument. One of the pieces of data is a spectrum: essentially just a list of values, plus a dictionary with some metadata. Once the data has been collected by the application it does not change, so both the list and the metadata can be considered immutable.
I’d like to use this to my advantage by heavily memoizing the functions that perform calculations on the spectrum. Here’s a toy example:
class Spectrum(object):
def __init__(self, values, metadata):
self.values = values
self.metadata = metadata
# self.values and self.metadata should not change after this point.
@property
def first_value(self):
return self.values[0]
def multiply_by_constant(self, c):
return [c*x for x in self.values]
def double(self):
return self.multiply_by_constant(2)
What I want is for each of these methods to be memoized by default. Is there some way (a metaclass?) to accomplish this without copying in one of these memoization decorators and writing @memoize
everywhere?