Search code examples
classvariablespythonprecompute

Pythonic way to only do work first time a variable is called


my Python class has some variables that require work to calculate the first time they are called. Subsequent calls should just return the precomputed value.

I don't want to waste time doing this work unless they are actually needed by the user. So is there a clean Pythonic way to implement this use case?

My initial thought was to use property() to call a function the first time and then override the variable:

class myclass(object):
    def get_age(self):
        self.age = 21 # raise an AttributeError here
        return self.age

    age = property(get_age)

Thanks


Solution

  • class myclass(object):
        def __init__(self):
            self.__age=None
        @property
        def age(self):
            if self.__age is None:
                self.__age=21  #This can be a long computation
            return self.__age
    

    Alex mentioned you can use __getattr__, this is how it works

    class myclass(object):
        def __getattr__(self, attr):
            if attr=="age":
                self.age=21   #This can be a long computation
            return super(myclass, self).__getattribute__(attr)
    

    __getattr__() is invoked when the attribute doesn't exist on the object, ie. the first time you try to access age. Every time after, age exists so __getattr__ doesn't get called