Socket being garbage collected too early

David Bolen db3l at
Fri Dec 17 02:38:29 CET 2004

Scott Robinson <dscottr at> writes:

> I have been having trouble with the garbage collector and sockets.

Are you actually getting errors or is this just theoretical?

> Unfortunately, google keeps telling me that the problem is the garbage
> collector ignoring dead (closed?) sockets instead of removing live
> ones.  My problem is
> 	x.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
> 	do_stuff(x.sock)
> def do_stuff(sock):
> 	sock_list.append(sock)
> once do_stuff finishes, x.sock disappears, and I can only believe it
> is being garbage collected.

Can you clarify this?  What do you mean by "x.sock" disappears?  Are
you getting a NameError later when trying to use "x.sock"?  

x.sock is just a name binding, so it is not really involved in garbage
collection (GC applies to the objects to which names are bound). 

In this case, you need to include much more in the way of code (a
fully running, but smallest possible, snippet of code would be best),
since the above can be interpreted many ways.  At the least, it's very
important to include information about the namespace within which
those two code snippets run if anyone is likely to be able to give you
a good answer.  Also, being very precise about the error condition you
are experiencing (including actual error messages, tracebacks, etc...)
is crucial.

Is 'x' referencing a local or global object, and does that socket code
occur within a method, a function, or what?  Also, in do_stuff, where
is sock_list defined?  Is it local, global?

If, as written, sock_list is a local name to do_stuff, then that
binding is going to disappear when do_stuff completes, thus, the list
to which it is bound will be destroyed, including all references to
objects that the list may contain.  So at that point, when you return
from do_stuff, the only reference to the socket object will be in
x.sock.  But if 'x' is also local to the function/method where the
call to do_stuff is, the name binding will be removed when the
function/method returns, at which point there will be no references to
the socket object, and yes, it will be destroyed.

But if sock_list is global, and continues to exist when do_stuff
completes, then the reference it contains to the socket will keep the
socket object alive even if you remove the x.sock binding.

-- David

More information about the Python-list mailing list