Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c4c0eae

Browse files
committed
give TextIOWrapper a repr that tells you the encoding
1 parent f2b55fb commit c4c0eae

3 files changed

Lines changed: 19 additions & 2 deletions

File tree

Lib/_pyio.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1399,6 +1399,9 @@ def __init__(self, buffer, encoding=None, errors=None, newline=None,
13991399
# - "bytes_..." for integer variables that count input bytes
14001400
# - "chars_..." for integer variables that count decoded characters
14011401

1402+
def __repr__(self):
1403+
return "<TextIOWrapper encoding={0}>".format(self.encoding)
1404+
14021405
@property
14031406
def encoding(self):
14041407
return self._encoding

Lib/test/test_io.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1354,6 +1354,12 @@ def test_constructor(self):
13541354
self.assertRaises(TypeError, t.__init__, b, newline=42)
13551355
self.assertRaises(ValueError, t.__init__, b, newline='xyzzy')
13561356

1357+
def test_repr(self):
1358+
raw = self.BytesIO("hello".encode("utf-8"))
1359+
b = self.BufferedReader(raw)
1360+
t = self.TextIOWrapper(b, encoding="utf-8")
1361+
self.assertEqual(repr(t), "<TextIOWrapper encoding=utf-8>")
1362+
13571363
def test_line_buffering(self):
13581364
r = self.BytesIO()
13591365
b = self.BufferedWriter(r, 1000)

Modules/_textio.c

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2171,6 +2171,14 @@ TextIOWrapper_truncate(PyTextIOWrapperObject *self, PyObject *args)
21712171
return PyObject_CallMethodObjArgs(self->buffer, _PyIO_str_truncate, NULL);
21722172
}
21732173

2174+
static PyObject *
2175+
TextIOWrapper_repr(PyTextIOWrapperObject *self)
2176+
{
2177+
CHECK_INITIALIZED(self);
2178+
return PyUnicode_FromFormat("<TextIOWrapper encoding=%S>", self->encoding);
2179+
}
2180+
2181+
21742182
/* Inquiries */
21752183

21762184
static PyObject *
@@ -2372,9 +2380,9 @@ PyTypeObject PyTextIOWrapper_Type = {
23722380
(destructor)TextIOWrapper_dealloc, /*tp_dealloc*/
23732381
0, /*tp_print*/
23742382
0, /*tp_getattr*/
2375-
0, /*tp_setattr*/
2383+
0, /*tps_etattr*/
23762384
0, /*tp_compare */
2377-
0, /*tp_repr*/
2385+
(reprfunc)TextIOWrapper_repr,/*tp_repr*/
23782386
0, /*tp_as_number*/
23792387
0, /*tp_as_sequence*/
23802388
0, /*tp_as_mapping*/

0 commit comments

Comments
 (0)