Proxy Pattern In Python
I have a lots of class implemented in my code. Now I realise that for each method invoked for all these classes I need to add a line: with service as object: So I'm trying to use
Solution 1:
I would use a decorator:
classProxy(object):
def__init__(self, object_a):
self._object_a = object_a
defdecorateEnterExit(self, obj, f):
definner(*args, **kwargs):
with obj as _:
return f(*args, **kwargs)
return inner
def__getattribute__(self, name):
obj = object.__getattribute__(self, '_object_a')
dee = object.__getattribute__(self, 'decorateEnterExit')
return dee(obj, getattr(obj, name))
That way the with will be only evaluated when the function is executed. The way you did it it would first evaluate the with (including exiting it) and then the function would be returned to be called. Now we return a function which will itself enter the with and call the function inside.
>>> Proxy(A('Ax')).hello()
Enter the function
hello Ax!
Exit the functionNote that you need to return self in your __enter__ method of A:
def__enter__(self):
print'Enter the function'return self
Solution 2:
You are missing a return statement in your __enter__ method, which should return an instance of your class(self).
As about the question, in your Proxy, it is likely, that result is evaluated after the context is closed. Try this to see what you actually return - is a bound method:
def__getattribute__(self, name):
service = object.__getattribute__(self, '_object_a')
with service as service:
result = getattr(service, name)
print result
return result
this will show
Enter the function
<bound method A.hello of <__main__.A object at 0x022A2950>>
Exit the functionAnd only then method is called, after __getattribute__ has returned it.
Post a Comment for "Proxy Pattern In Python"