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

A really light implementation of lazy load technique, yet powerful and conveniet.

Simply call this:

var1 = superlazy('key', default_value)

Your var1 will be loaded in load_setting(key) when accessed first time.

That's it. No subclassing is needed, no declaration is needed. Value type is auto detected and handled gracefully. str, int, list, dict can all be lazily loaded from anywhere you want now.

Python, 64 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def load_setting(key):
    # Just some dummy values for demo
    if key == 'key':
        return '123123'
    elif key == 'limit':
        return 123123
    elif key == 'dummylist':
        return [1, 2, 3, 4, 5]
    elif key == 'crap':
        return {'good': "boy"}

def superlazy(key, default):
    class T(type(default)):
        @staticmethod
        def __loader__():
            ret = load_setting(key)
            if ret:
                setattr(T, '__cache__', ret)
            delattr(T, '__loader__')
        
    def force(k, v):
        def _wrapper(*args, **kwargs):
            if hasattr(T, '__loader__'):
                T.__loader__()
            if hasattr(T, '__cache__'):
                c = T.__cache__
                func = getattr(c, k)
                return func(*args[1:], **kwargs)
            
            return v(*args, **kwargs)

        return _wrapper
    
    t = T(default)
    for k, v in type(default).__dict__.iteritems():
        if (k in ['__doc__']): continue
        setattr(T, k, force(k, v))
    return t

# Lazy string
a = superlazy("key", 'hahahaha')
print a, isinstance(a, str)

# Lazy int
b = superlazy("limit",9)
print 1 + b, isinstance(b, int)
print str(b)

# Lazy list
c = superlazy("dummylist", [1, 2, 3])
print c
print c[0]
print len(c)

# Lazy dict
d = superlazy("crap", {'a': 1, 'b': 2, 'c': 3})
print isinstance(d, dict)
print d
print d.get('a')

# Not existed lazy int, default value is used
e = superlazy("wer", 321)
print isinstance(e, int)
print e

1 comment

a 13 years, 1 month ago  # | flag

setattr(T, '__cache__', ret) should be written as T.__cache__ = ret delattr(T, '__loader__') shoulc be written as del T.__loader__

Created by Russell on Tue, 16 Mar 2010 (MIT)
Python recipes (4591)
Russell's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks