[New-bugs-announce] [issue43834] Use context manager in StringIO example

John Hagen report at bugs.python.org
Tue Apr 13 16:02:35 EDT 2021


New submission from John Hagen <johnthagen at gmail.com>:

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.

https://docs.python.org/3/library/io.html#io.StringIO.getvalue

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.

----------
assignee: docs at python
components: Documentation
messages: 391000
nosy: John Hagen, docs at python
priority: normal
severity: normal
status: open
title: Use context manager in StringIO example
type: enhancement
versions: Python 3.10

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43834>
_______________________________________


More information about the New-bugs-announce mailing list