[issue15216] Support setting the encoding on a text stream after creation

Nick Coghlan report at bugs.python.org
Tue Aug 7 07:34:02 CEST 2012


Nick Coghlan added the comment:

The reason I marked this as a release blocker for 3.4 is because it's a key piece of functionality for writing command line apps which accept an encoding argument. I'll use "high" instead.

An interesting proposal was posted to the python-dev thread [1]: using self.detach() and self.__init__() to reinitialise the wrapper *in-place*.

With that approach, the pure Python version of set_encoding() would look something like this:

    _sentinel = object()
    def set_encoding(self, encoding=_sentinel, errors=_sentinel):
        if encoding is _sentinel:
            encoding = self.encoding
        if errors is _sentinel:
            errors = self.errors
        self.__init__(self.detach(),
                      encoding, errors,
                      self._line_buffering,
                      self._readnl,
                      self._write_through)

(The pure Python version currently has no self._write_through attribute - see #15571)

Note that this approach addresses my main concern with the use of detach() for this: because the wrapper is reinitialised in place, old references (such as the sys.__std*__ attributes) will also see the change.

Yes, such a function would need a nice clear warning to say "Calling this may cause data loss or corruption if used without due care and attention", but it should *work*. (Without automatic garbage collection, the C implementation would need an explicit internal "reinitialise" function rather than being able to just use the existing init function directly, but that shouldn't be a major problem).

[1] http://mail.python.org/pipermail/python-ideas/2012-August/015898.html

----------
priority: normal -> high

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15216>
_______________________________________


More information about the Python-bugs-list mailing list