object - Python recursive proxy -
hopefully should explain i'm trying achieve
class a(object): def hello(self): print "hello" = a() a.b = a() a.b.c = a() a.b.d = [] a.b.d.append(a()) p = proxy(a) print p.b "b accessed" <__main__.a object @ 0xb73f3bec> print p.b.c "b accessed" "c accessed" <__main__.a object @ 0xb73f3dec> print p.b.d "b accessed" "d accessed" [<__main__.a object @ 0xb73f3bcc>] print p.b.d[0] "b accessed" "d accessed" <__main__.a object @ 0xb73e766c> print p.b.d[0].hello() "b accessed" "d accessed" "hello called" "hello"
basically far walk down structure keeps returning proxy objects. best if created these proxy objects when attribute accessed first time , stored on 'parent'. goal of can logic before method called on (nested) object
i had at: http://code.activestate.com/recipes/496741-object-proxying/ first layer, , couldn't see how manipulate work need.
use global cache, , create proxy factory method first checks global cache before creating new proxies.
note solution not store child proxy objects on 'parent'. instead, uses id(obj)
trick retrieve object cache whatever how deepest is.
not_found = object() # global proxy cache _id2obj_dict = {} def remember(oid, proxy): _id2obj_dict[oid] = proxy return oid def id2obj(oid): print("accessing cahed object") return _id2obj_dict[oid] class a(object): def hello(self): print "hello" class proxy(object): @classmethod def create(cls, obj): ''' object factory ''' oid = id(obj) if oid in _id2obj_dict: return id2obj(oid) proxy = cls() proxy.obj = obj remember(oid, proxy) return proxy def __getattr__(self, attr): prop = getattr(self.obj, attr, not_found) if prop not_found: raise attributeerror() print("{} accessed".format(attr)) proxy = proxy.create(prop) return proxy def __getitem__(self, index): prop = self.obj.__getitem__(index) proxy = proxy.create(prop) return proxy def __call__(self): print("{} called".format(self.obj.__name__)) return self.obj() = a() a.b = a() a.b.c = a() a.b.d = [] a.b.d.append(a()) p = proxy.create(a)
Comments
Post a Comment