Patch to fix the underlying issue I mentioned in . After calling detach() on one of the BufferedIOBase wrappers or a TextIOWrapper, most operations will raise an exception. My patch ensures the following operations are still usable, because they are documented and it doesn’t make sense to disable them: repr(stream) stream.encoding stream.errors stream.line_buffering
The issue is still here. >>> f = open('/dev/null') >>> f <_io.TextIOWrapper name='/dev/null' mode='r' encoding='UTF-8'> >>> f.buffer.detach() <_io.FileIO name='/dev/null' mode='rb' closefd=True> >>> f Traceback (most recent call last): File "", line 1, in ValueError: raw stream has been detached Python implementation works. >>> import _pyio >>> f = _pyio.open('/dev/null') >>> f <_pyio.TextIOWrapper name='/dev/null' mode='r' encoding='UTF-8'> >>> f.buffer.detach() <_io.FileIO name='/dev/null' mode='rb' closefd=True> >>> f <_pyio.TextIOWrapper mode='r' encoding='UTF-8'> >>> f = _pyio.open('/dev/null') >>> f.detach() <_pyio.BufferedReader name='/dev/null'> >>> f <_pyio.TextIOWrapper mode='r' encoding='UTF-8'> >>> f = _pyio.open('/dev/null', 'rb') >>> f <_pyio.BufferedReader name='/dev/null'> >>> f.detach() <_io.FileIO name='/dev/null' mode='rb' closefd=True> >>> f <_pyio.BufferedReader> I would be good to make Python and C implementation match.
Damn, detaching the intermediate buffered stream is a bit more awkward. The difference between the “io” and “_pyio” implementations boils down to: * io.BufferedReader/Writer/RWPair.name properties raise a ValueError if the stream is detached * _pyio._BufferedIOMixin.name property returns “self.raw.name”. When detached, “self.raw” is None, so this causes an AttributeError. This is significant because io.TextIOWrapper.__repr__() only handles AttributeError when accessing “self.buffer.name”. The best option that I can think of to fix this is to make all the repr() implementations handle this ValueError exception.
Here is patch v2, which ignores any exception derived from the Exception base class when reading the self.name etc properties. I’m interested what people think of this approach.