Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing sockets in python

I'm modifying Python code that have this form:

def foo(self):
    try:
        connect socket
    except Exception, e:
        some error reporting stuff
        return an error

    use the socket
    do some other stuff

    if some condition:
        return

    do some more stuff
    socket.close()
    return normally

Coming from Java I would like to have a try - finally around the whole thing to make sure that the socket is closed. Should this code also have that or is it some kind of Pythonic magic happening in the background that makes it so that you don't have to?

I read in the python docs that sockets are closed when they are garbage collected. But relying on the garbage collector to close your sockets doesn't feel so good.

like image 870
Jörgen Lundberg Avatar asked Dec 13 '22 02:12

Jörgen Lundberg


2 Answers

You can use a try-finally block, which was added in Python 2.5:

try:
    open socket
    do stuff with socket
finally:
    close socket

Or you can use the with statement, which was added in Python 2.6 (and can be used in 2.5 with a from __future__ import with_statement declaration):

with open_the_socket() as s:
    use s

This will automatically close the socket when the inner block is exited, whether it's exited normally or via an exception, provided that the socket class closes in its __exit__() method.

As of Python 2.7.2 the __exit__() method is not implemented on the socket class.

like image 119
Adam Rosenfield Avatar answered Dec 15 '22 17:12

Adam Rosenfield


You seem to be wanting the finally block added to try/except in 2.5

http://docs.python.org/whatsnew/2.5.html#pep-341-unified-try-except-finally

You are correct that relying on the autoclose when garbage collected is a bad practice, it's best to close them when you are done with them. A try/finally is a good way to do it.

Don't forget to call shutdown() before close().

like image 34
Vinko Vrsalovic Avatar answered Dec 15 '22 17:12

Vinko Vrsalovic