4 ms·
try: try: sock.shutdown() finally: sock.close() except OSError: pass Or, given the .close method from
by _ZeD_ 5y ago
try:
try:
sock.shutdown()
finally:
sock.close()
except OSError:
pass
Or, given the .close method
from contextlib import closing
try:
with closing(sock):
sock.shutdown()
except OSError:
pass
- masklinn 5y ago`contextlib.ignore` could also be useful here e.g. with contextlib.ignore(OSError),\ closing(sock): sock.shutdown()
- heavyset_go 5y agocontextlib.ignore was renamed to contextlib.suppress
- dncornholio 5y agoThere is nothing wrong with the proposed solution though? I think you are over doing it IMHO, creating unnecessary complexion.
- masklinn 5y agoI’ve no idea what you’re to trying to express. My comment does not imply there’s anything wrong with the comment, it just uses a tool from the standard library to reduce nesting and (as far as i’m concerned) make it more explicit and upfront. And support the original query.
- _ZeD_ 5y agowell, the nested try: ... finally: gave you something to think about: why do you have a "sock" object that you need to explicitly close "manually"? I didn't look at the source, it can be for a number of reasons. But I suspect some long lived sock object shared between functions. Something that could be wrapped in a context manager. like with MyCtxMgr() as my_ctx_mgr: # open the socket, init, etc... my_ctx_mgr.do_stuff() # internally it has access my_ctx_mgr.do_another_stuff() # to the opened socket external_function(my_ctx_mgr.get_sock()) # and can pass it # in the __exit__ actually close the socket, dealing with the OSError calling a barebone "obj.close()" is a code smell IMHO
- deleted 5y ago[deleted]