[issue24911] Context manager of socket.socket is not documented
STINNER Victor
report at bugs.python.org
Wed Feb 17 06:25:01 EST 2016
STINNER Victor added the comment:
I reviewed the patch.
> It would also be cool if you can add a short code snippet somewhere:
The socket module has examples.
Why not modifying these examples to promote the context manager protocol?
Example:
--------
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s
# use with to ensure that the socket is closed, especially on error
with s:
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
--------
The second "with conn:" is maybe overkill. What do you think?
For a client connection, usually I prefer to explicitly close the socket (even if I use "with conn:") to get exception on my ".close()" line, instead of getting an exception from the context manager, which is harder to understand.
----------
nosy: +haypo
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24911>
_______________________________________
More information about the Python-bugs-list
mailing list