1CCqZOLR7Jog7kDLe0gJrD changeset

Changeset363730643234 (b)
ParentNone (a)
ab
0+# -*- coding: utf-8 -*-
0+
0+_instances = {}
0+
0+class Wrapper(object):
0+
0+    def __new__(cls, **kwargs):
0+        instance = object.__new__(cls)
0+        instance.__init__(**kwargs)
0+        if instance.uuid in _instances:
0+            cached = _instances[instance.uuid]
0+            for attr in kwargs.items():
0+                setattr(cached, *attr)
0+            return cached
0+        else:
0+            _instances[instance.uuid] = instance
0+            return instance
0+
0+    @property
0+    def uuid(self):
0+        raise NotImplementedError()
0+
0+class Test(Wrapper):
0+
0+    def __init__(self, name=None):
0+        self.name = name
0+
0+    @property
0+    def uuid(self):
0+        return self.name
0+
0+id(Test(name='toto')) == Test(name='toto')
0+t1 = Test(name='toto')
0+t2 = Test(name='toto')
0+
0+print id(t1) == id(t2)
0+t1.name = 'tata'
0+print t2.name
...
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
--- Revision None
+++ Revision 363730643234
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+
+_instances = {}
+
+class Wrapper(object):
+
+ def __new__(cls, **kwargs):
+ instance = object.__new__(cls)
+ instance.__init__(**kwargs)
+ if instance.uuid in _instances:
+ cached = _instances[instance.uuid]
+ for attr in kwargs.items():
+ setattr(cached, *attr)
+ return cached
+ else:
+ _instances[instance.uuid] = instance
+ return instance
+
+ @property
+ def uuid(self):
+ raise NotImplementedError()
+
+class Test(Wrapper):
+
+ def __init__(self, name=None):
+ self.name = name
+
+ @property
+ def uuid(self):
+ return self.name
+
+id(Test(name='toto')) == Test(name='toto')
+t1 = Test(name='toto')
+t2 = Test(name='toto')
+
+print id(t1) == id(t2)
+t1.name = 'tata'
+print t2.name