2

I have a huge config file that I need to parse to get different configuration parameters at several classes/modules. I have created a separate module with function to do the parsing and other modules can call this to get the parsed file output.

I have come across this post Understanding __get__ and __set__ and Python descriptors which says property descriptors get can be used to cache expensive operations.

Here is what I am trying to do:

class Lazy(object):
"""Lazy attribute evaluation decorator class"""
    def __init__(self, f):
        self.f = f
        self.cache = {}
    def __get__(self, instance, owner):
        if instance not in self.cache:
            self.cache[instance] = self.f(instance)
        return self.cache[instance]

then in another class I am doing this:

def load_config_file(self):
    """
    """
    with open('/etc/test.json') as json_file:
        return json.loads(json_file)

How can I decorate the load_config_file such that the actual load from json file is called only once no matter how many modules/classes call this?

If I do

@Lazy
def load_config_file(self, file):

how would I pass the instance parameter? Can someone explain me how to achieve this?

Community
  • 1
  • 1
as3rdaccount
  • 3,473
  • 8
  • 35
  • 57
  • possible duplicate of [What is memoization and how can I use it in Python?](http://stackoverflow.com/questions/1988804/what-is-memoization-and-how-can-i-use-it-in-python) – roippi Nov 12 '14 at 21:04
  • Descriptors only work when used as class attributes. You could just write a memoization decorator. – BrenBarn Nov 12 '14 at 21:05
  • Yeah, as BrenBarn said, you're mixing two different things here and it's unclear which one are you after. Do you want just memoization? Then in fact you don't need the descriptor. Or do you really want an example of how can one realize memoization using descriptors? – BartoszKP Nov 12 '14 at 21:18
  • https://github.com/openstack/horizon/blob/master/horizon/utils/memoized.py I have seen one example of memoize here. Can someone explain me how it works? My confusion is cache will be set to {} everytime the decorated function is called, no? – as3rdaccount Nov 12 '14 at 21:20
  • @brotherofmysister I cannot understand your case: do you have just a JSON file to parse? Why use decorator here? You can use a singleton that load file on a dictionary (or extend a dictionary) and serve the other objects. – Michele d'Amico Nov 12 '14 at 21:32
  • @brotherofmysister cache will be set to {} just when decorator is instantiated: just when function is decorated and not executed. – Michele d'Amico Nov 12 '14 at 21:55

0 Answers0