It seems like it would be only natural to do something like:
with socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
but Python doesn't implement a context manager for socket. Can I easily use it as a context manager, and if so, how?
It seems like it would be only natural to do something like:
with socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
but Python doesn't implement a context manager for socket. Can I easily use it as a context manager, and if so, how?
Please have a look on following snippets, for both TCP and UDP sockets
So that you can use them in following way:
I've also tried to emphasise the difference in behaviour and approach to term 'connection' between TCP and UDP in method names.
The socket module is just a wrapper around the BSD socket interface. It's low-level, and does not really attempt to provide you with a handy or easy to use Pythonic API. You may want to use something higher-level.
That said, it does in fact implement a context manager:
But you need to use Python 3.
For Python 2 compatibility you can use
contextlib
.The
socket
module is fairly low-level, giving you almost direct access to the C library functionality.You can always use the
contextlib.contextmanager
decorator to build your own:or use
contextlib.closing()
to achieve the same effect:but the
contextmanager()
decorator gives you the opportunity to do other things with the socket first.Python 3.x does make
socket()
a context manager, even though the documentation fails to mention that. See thesocket
class in the source code, which adds__enter__
and__exit__
methods.