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.
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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With