Revision 363730643234 () - Diff

Link to this snippet: https://friendpaste.com/1CCqZOLR7Jog7kDLe0gJrD
Embed:
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
# -*- 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