Python object proxying: how to access proxy -


i found this recipe create proxy class. i've used wrap custom object , overload properties , attach new attributes proxy. however, when call method on proxy (from within proxy class), end being delegated wrappee not want.

is there way of accessing or storing reference proxy?

here's code (untested) demonstrate problem.

class myobject(object):   @property   def value(self):     return 42  class myobjectproxy(proxy): # see link above   def __getattribute__(self, attr):     # problem `self` refers proxied      # object , throws attributeerror. how      # can reference myobjectproxy.another_value()?     if attr == 'value':  return self.another_value() # return method or attribute, doesn't matter (same effect)     return super(myobjectproxy, self).__getattribute__(attr)    def another_value(self):     return 21  o = myobject() p = myobjectproxy(o) print o.value print p.value 

in sense problem proxy works good, hiding own methods/attributes , posing proxied object (which should do)...

update

based on comments below, changed __getattribute__ this:

def __getattribute__(self, attr):     try:         return object.__getattribute__(self, attr)     except attributeerror:         return super(myobjectproxy, self).__getattribute__(attr) 

this seems trick now, better add directly proxy class.

the reason code goes wrong loop in __getattribute__. want override __getattribute__ can reach properties in proxy class itself. let's see.

when call p.value __getattribute__ called. comes here if attr == 'value': return self.another_value(). here need call another_value enter __getattribute__ again.

this time comes here return super(myobjectproxy, self).__getattribute__(attr). call proxy's __getattribute__, , tries fetch another_value in myobject. exceptions occur.

you can see traceback goes return super(myobjectproxy, self).__getattribute__(attr) should not go to.

traceback (most recent call last):   file "proxytest.py", line 22, in <module>     print p.value   file "proxytest.py", line 13, in __getattribute__     if attr == 'value':  return self.another_value() # return method or attribute, doesn't matter (same effect)   file "proxytest.py", line 14, in __getattribute__     return super(myobjectproxy, self).__getattribute__(attr)   file "/home/hugh/m/tspace/proxy.py", line 10, in __getattribute__     return getattr(object.__getattribute__(self, "_obj"), name) attributeerror: 'myobject' object has no attribute 'another_value' 

edit:
change line of code if attr == 'value': return self.another_value() if attr == 'value': return object.__getattribute__(self, 'another_value')().


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -