This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author vstinner
Recipients berker.peksag, desbma, docs@python, martin.panter, vstinner, yselivanov
Date 2016-02-17.11:25:00
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1455708301.04.0.952164054205.issue24911@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2016-02-17 11:25:01vstinnersetrecipients: + vstinner, docs@python, berker.peksag, martin.panter, desbma, yselivanov
2016-02-17 11:25:01vstinnersetmessageid: <1455708301.04.0.952164054205.issue24911@psf.upfronthosting.co.za>
2016-02-17 11:25:01vstinnerlinkissue24911 messages
2016-02-17 11:25:00vstinnercreate