[issue7464] circular reference in HTTPResponse by urllib2

Kristján Valur Jónsson report at bugs.python.org
Fri Dec 11 00:16:29 CET 2009

Kristján Valur Jónsson <kristjan at ccpgames.com> added the comment:

I have two solutions for this problem.  The first is a mundane one, and 
what I employed in our production environment:
class RecvAdapter(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped
    def recv(self, amt):
        return self.wrapped.read(amt)
    def close(self):

    fp = socket._fileobject(RecvAdapter(r), close=True)

The second solution is a bit more interesting.  It involves applying 
what I call a weakmethod: A bound method that holds a weak ref to the 
object instance:

import weakref
class WeakMethod(object):
    def __init__(self, bound):
        self.weakself = weakref.proxy(bound.im_self)
        self.methodname = bound.im_func.func_name
    def __call__(self, *args, **kw):
        return getattr(self.weakself, self.methodname)(*args, **kw)

We then do:
    r.recv = WeakMethod(r.read)
    fp = socket._fileobject(r, close=True)

I've had many uses for a WeakMethod through the years.  I wonder if such 
a class might be considered useful enough to be put into the weakref 

keywords: +patch

Python tracker <report at bugs.python.org>

More information about the Python-bugs-list mailing list