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

This useless hack allows normal functions to be attached to a 'ThunkSpace' which causes the function to be lazily evaluated when the thunk is referenced. It is just a experiment using closures and descriptors to try and change python function call syntax.

Python, 39 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
class ThunkSpace(object):
    """
    A ThunkSpace for Python. Assigning functions to an instance of ThunkSpace
    will turn the function into a lazily evaluated attribute.
    """
        
    def __setattr__(self, name, func):
        def delete(self):
            delattr(self.__class__, name)
        def get(self): 
            return func()
        def set(self, new_func):
            def get(self): 
                return new_func()
            setattr(self.__class__, name, property(get, set, delete))
        setattr(self.__class__, name, property(get, set, delete))
            
    
if __name__ == "__main__":    

    def lazy_something():
        return "lazy_something was called."
    
    def lazy_something_else():
        return "lazy_something_else was called."
    
    #create a ThunkSpace
    ts = ThunkSpace()
    
    #create an attribute named lazy_func, which when referenced, will call 
    #lazy_something
    ts.lazy_func = lazy_something
    
    print ts.lazy_func
    
    #the lazy_func attribute can be replaced with another function...
    ts.lazy_func = lazy_something_else
    
    print ts.lazy_func
    

You probably never want to use this recipe. :-)

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

Required Modules

  • (none specified)

Other Information and Tasks