Dictionary storage

I want to design my new Python method such that the mainline method (here labelled “main_meth”) executes a separate calculation method (here labelled “calc_meth”. “Main_meth” will call “calc_meth” several thousand times.

The issue is that “calc_meth” requires a very large of ammount of data to be loaded from the database into a dictionary, on which the calculations are based. If “calc_meth” has to load all the data from the database into the dictionary every time it is called, it will obviously run slowly.

Is it possible to code these methods so that the dictionary in “calc_meth” is only loaded the first time it is called, not every time ? Any advice would be greatly appreciated, please.

Yes, what you are trying to do is called lazy initialization and it is very common. If your application is single threaded then it is pretty simple. Just start the dictionary out as None and do a check for the dictionary to be None before using it. You can have a private helper function to initialize it:

class SomeClass(object):

  _MY_DATA = None

  def _load_data():
    return ...  # costly database call

  def get_my_data(self):
    if self._MY_DATA is None:
      self._MY_DATA = _load_data()
    return cls._MY_DATA

  def calc_meth(...):
    # use get_my_data whenever you need the dict