This code works as expected, but can it cause a memory leak?
class Method(object):
method = []
def call(self,method,*args,**kwargs):
kwargs.update({'access_token': self.access_token})
print method,args,kwargs
def __getattr__(self,name):
cp = Method()
cp.access_token = self.access_token
cp.method = self.method + [name]
return cp
def __call__(self,*args,**kwargs):
return self.call('.'.join(self.method),*args,**kwargs)
class Api(Method):
access_token = 'setups on init'
a=Api()
a.get()
a.set(data=1)
Or will Method instance go to garbage after calling?
1 Answer 1
You don't have a memory leak.
You are simply returning a callable object; when you no longer reference it it'll be cleaned up automatically.
The __getattr__ method doesn't add any more references to the object other than the local variable name. That reference is cleared when the function exits.
The a.get() and a.set() expressions only hold a reference to the object for long enough to look up the __call__ method and invoke it. When the __call__ method returns, the number of references to the Method() instance drops to 0 and the object is cleared.
2 Comments
a.friends.get_related() (may be up to 5)? Will all instaces (except a) be cleaned?