Welcome, guest | Sign In | My Account | Store | Cart

This class provides thunk-like behavior in standard Python.

It allows a function to be evaluated only when needed, and the return value cached, or memoized, until explicitly deleted.

Python, 44 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class LazySpace(object):
    def __init__(self, function):
        self.__dict__["function"] = function
        self.__dict__["arguments"] = {}
        
    def __call__(self, *args, **kw):
        arg_pack = args, kw
        return arg_pack
    
    def __setattr__(self, key, arg_pack):
        self.arguments[key] = arg_pack
        
    def __getattr__(self, key):
        args, kw = self.arguments[key]
        r = self.__dict__[key] = self.function(*args, **kw)
        return r


if __name__ == "__main__":

    def something_we_might_need(a,b,x=0):
        print 'Executing something_we_might_need'
        return "AB=%s, X=%s" % ((a*b),x)
        
        
    #create a lazy space for storing results from this function
    lz = LazySpace(something_we_might_need)
    
    #call our lazy function, and assign its results into an attribute in the 
    #lazy namespace
    lz.ab = lz(1,2,x=1)
    
    #print the attribute (notice this is when the function is first run)
    print lz.ab
    
    #next time the attibute is accessed, there is no need for the function to 
    #run again.
    print lz.ab
    
    #deleting the attribute will remove it from the lazy space, and force the 
    #function to run again, next time the attribute is accessed.
    del lz.ab
    
    print lz.ab
    
    

This class is useful for storing potentially costly resources, which may or may not be needed in any given run of the application. Eg, image files, textures, sound files, urls, etc.

It allows these types of resources to be stored in a common namespace, and only actually fetched/loaded/processed when and if they are used.

Created by S W on Wed, 18 Jan 2006 (PSF)
Python recipes (4591)
S W's recipes (20)

Required Modules

  • (none specified)

Other Information and Tasks