[Python-checkins] r68668 - in sandbox/trunk/io-c: _textio.c test_io.py
antoine.pitrou
python-checkins at python.org
Sat Jan 17 21:59:16 CET 2009
Author: antoine.pitrou
Date: Sat Jan 17 21:59:16 2009
New Revision: 68668
Log:
Be sure the encoding attribute on TextIOWrapper objects is always non-NULL
Modified:
sandbox/trunk/io-c/_textio.c
sandbox/trunk/io-c/test_io.py
Modified: sandbox/trunk/io-c/_textio.c
==============================================================================
--- sandbox/trunk/io-c/_textio.c (original)
+++ sandbox/trunk/io-c/_textio.c Sat Jan 17 21:59:16 2009
@@ -629,19 +629,26 @@
if (encoding == NULL) {
/* Try os.device_encoding(fileno) */
- PyObject *os = PyImport_ImportModule("os");
- if (os == NULL)
- goto error;
- self->encoding = PyObject_CallMethod(
- os, "device_encoding", "N",
- PyObject_CallMethod(buffer, "fileno", NULL));
- Py_DECREF(os);
+ PyObject *fileno, *os;;
+ fileno = PyObject_CallMethod(buffer, "fileno", NULL);
/* Ignore any error */
/* XXX only AttributeError and UnsupportedOperation */
- if (self->encoding == NULL)
+ if (fileno == NULL)
PyErr_Clear();
- else if (!PyUnicode_Check(self->encoding))
- Py_CLEAR(self->encoding);
+ else {
+ os = PyImport_ImportModule("os");
+ if (os == NULL) {
+ Py_DECREF(fileno);
+ goto error;
+ }
+ self->encoding = PyObject_CallMethod(os, "device_encoding",
+ "N", fileno);
+ Py_DECREF(os);
+ if (self->encoding == NULL)
+ goto error;
+ else if (!PyUnicode_Check(self->encoding))
+ Py_CLEAR(self->encoding);
+ }
}
if (encoding == NULL && self->encoding == NULL) {
/* try locale.getpreferredencoding() */
@@ -662,6 +669,15 @@
}
if (self->encoding != NULL)
encoding = _PyUnicode_AsString(self->encoding);
+ else if (encoding != NULL) {
+ self->encoding = PyUnicode_FromString(encoding);
+ if (self->encoding == NULL)
+ goto error;
+ }
+ else {
+ PyErr_SetString(PyExc_IOError,
+ "could not determine default encoding");
+ }
if (errors == NULL)
errors = "strict";
Modified: sandbox/trunk/io-c/test_io.py
==============================================================================
--- sandbox/trunk/io-c/test_io.py (original)
+++ sandbox/trunk/io-c/test_io.py Sat Jan 17 21:59:16 2009
@@ -1196,6 +1196,15 @@
t.write("A\rB")
self.assertEquals(r.getvalue(), b"XY\nZA\rB")
+ def testEncoding(self):
+ # Check the encoding attribute is always set, and valid
+ b = io.BytesIO()
+ t = io.TextIOWrapper(b, encoding="utf8")
+ self.assertEqual(t.encoding, "utf8")
+ t = io.TextIOWrapper(b)
+ self.assert_(t.encoding is not None)
+ codecs.lookup(t.encoding)
+
def testEncodingErrorsReading(self):
# (1) default
b = io.BytesIO(b"abc\n\xff\n")
More information about the Python-checkins
mailing list