1

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?

Martijn Pieters
1.1m326 gold badges4.2k silver badges3.5k bronze badges
asked Aug 13, 2013 at 11:23

1 Answer 1

2

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.

answered Aug 13, 2013 at 11:26
Sign up to request clarification or add additional context in comments.

2 Comments

Even if i call a.friends.get_related() (may be up to 5)? Will all instaces (except a) be cleaned?
@eri: yes, because all references by the interpreter are temporary and are properly cleared. Note that regular Python methods are wrapper objects too (see the descriptor howto) and if there were any memory leaks in calling expressions Python would have died from a million memory leak problems years ago. :-)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.