COW example...
[bitbake.git] / lib / bb / COW.py
1 # ex:ts=4:sw=4:sts=4:et
2 # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
3 """
4 This is a copy on write dictionary which abuses classes to be nice and fast.
5
6 Please Note: Be careful when using mutable types (ie Dict and Lists). The copy on write stuff only kicks in on Assignment.
7 """
8
9 from inspect import getmro
10
11 class COWMeta(type):
12     def __str__(cls):
13         return "<COW Level: %i Current Keys: %i>" % (cls.__count__, len(cls.__dict__))
14     __repr__ = __str__
15
16     def cow(cls):
17         class C(cls):
18             __count__ = cls.__count__ + 1
19         return C
20
21     def __setitem__(cls, key, value):
22         setattr(cls, key, value)
23     def __getitem__(cls, key):
24         return getattr(cls, key)
25     def haskey(cls, key):
26         return hasattr(cls, key)
27
28     def iter(cls, type):
29         for key in dir(cls):
30             if key.startswith("__"):
31                 continue
32
33             if type == "keys":
34                 yield key
35             if type == "values":
36                 yield cls[key]
37             if type == "items":
38                 yield (key, cls[key])
39         raise StopIteration()
40
41     def iterkeys(cls):
42         return cls.iter("keys")
43     def itervalues(cls):
44         return cls.iter("values")
45     def iteritems(cls):
46         return cls.iter("items")
47     copy = cow
48
49 class COWBase(object):
50     __metaclass__ = COWMeta
51     __count__ = 0
52
53 if __name__ == "__main__":
54     a = COWBase
55     print a
56     a['a'] = 'a'
57     
58     b = a.copy()
59     print b
60     b['b'] = 'b'
61
62     for x in b.iteritems():
63         print x
64     print
65
66     b['a'] = 'c'
67
68     for x in b.iteritems():
69         print x
70     print
71