[issue43260] Never release buffer when MemoryError in print()
Eryk Sun
report at bugs.python.org
Fri Feb 19 04:38:56 EST 2021
Eryk Sun <eryksun at gmail.com> added the comment:
The sys.stdout TextIOWrapper is stuck in a bad state. When the write() method is called with an ASCII string, it implements an optimization that stores a reference to the str() object in the internal pending_bytes instead of immediately encoding the string. Subsequently _textiowrapper_writeflush() attempts to create a bytes object for this ASCII string, but PyBytes_FromStringAndSize fails with a memory error. It's stuck in this state because it will never be able to flush the string.
The first workaround I thought of was to call to detach() to rewrap sys.stdout.buffer with a new TextIOWrapper instance, but detach() attempts to flush and fails. A hacky but simple and effective workaround is to just re-initialize the wrapper. For example:
sys.stdout.__init__(sys.stdout.buffer, sys.stdout.encoding,
sys.stdout.errors, None, True)
This clears the internal pending_bytes.
----------
components: +IO
nosy: +eryksun
priority: normal -> high
versions: +Python 3.10, Python 3.9
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43260>
_______________________________________
More information about the Python-bugs-list
mailing list