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.

Title: Use context manager in StringIO example
Type: enhancement Stage: resolved
Components: Documentation Versions: Python 3.10
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: docs@python Nosy List: John Hagen, benjamin.peterson, docs@python, rhettinger, stutzbach
Priority: normal Keywords: patch

Created on 2021-04-13 20:02 by John Hagen, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Pull Requests
URL Status Linked Edit
PR 25401 closed John Hagen, 2021-04-14 12:11
Messages (4)
msg391000 - (view) Author: John Hagen (John Hagen) * Date: 2021-04-13 20:02
The example for StringIO currently manually closes the object rather than using a context manager. Since this is likely the first code that a new user encounters and context managers reduce error-prone situations, I think it would be helpful to show usage as a context manager.

Something like:

import io

with io.StringIO() as output:
    output.write('First line.\n')
    print('Second line.', file=output)

    # Retrieve file contents -- this will be
    # 'First line.\nSecond line.\n'
    contents = output.getvalue()

# Context manager will automatically close
# object and discard memory buffer --
# .getvalue() will now raise an exception.
msg391415 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2021-04-19 23:25
Let's leave the example as-is.   The principal use case for these objects is to pass them into other APIs that require file-like objects.  Those can't always be put in a context manager.  For this example, we mainly want to communicate that getvalue() must be called before the object is closed.  The current form communicates that clearly.

Thanks for the suggestion.
msg391416 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2021-04-19 23:27
Except for that, the PR looks fine.  Leaving this open to see what Benjamin thinks.
msg391417 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2021-04-20 00:32
I agree that closing or using a context manager with StringIO (or BytesIO) is not something one normally has to do, so it doesn't need to be in the example.
Date User Action Args
2022-04-11 14:59:44adminsetgithub: 88000
2021-04-20 00:32:20benjamin.petersonsetstatus: open -> closed
resolution: rejected
messages: + msg391417
2021-04-19 23:27:32rhettingersetstatus: closed -> open
resolution: rejected -> (no value)
messages: + msg391416
2021-04-19 23:25:56rhettingersetstatus: open -> closed

nosy: + rhettinger
messages: + msg391415

resolution: rejected
stage: patch review -> resolved
2021-04-16 20:34:13terry.reedysetnosy: + benjamin.peterson, stutzbach
2021-04-14 12:11:28John Hagensetkeywords: + patch
stage: patch review
pull_requests: + pull_request24133
2021-04-13 20:02:34John Hagencreate