[docs] [issue24911] Context manager of socket.socket is not documented
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?
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s
# use with to ensure that the socket is closed, especially on error
conn, addr = s.accept()
print('Connected by', addr)
data = conn.recv(1024)
if not data: break
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.
Python tracker <report at bugs.python.org>
More information about the docs