views:

185

answers:

3

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.

+1  A: 

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().

Vinko Vrsalovic
+5  A: 

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.

Adam Rosenfield
Python has always had try-finally. 2.5 unified try-except-finally http://docs.python.org/reference/compound_stmts.html#the-try-statement
JimB
A: 

In addition to the try/finally block, consider setting a socket default timeout that will automatically close the socket(s) after your specified time.

http://docs.python.org/library/socket.html?highlight=setdefaulttimeout#socket.setdefaulttimeout

twils