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.