2 An implementation of the I/O abstract base classes hierarchy
3 as defined by PEP 3116 - "New I/O"
5 Classes defined here: IOBase, RawIOBase.
7 Written by Amaury Forgeot d'Arc and Antoine Pitrou
11 #define PY_SSIZE_T_CLEAN
13 #include "structmember.h"
14 #include "_iomodule.h"
17 * IOBase class, an abstract class
24 PyObject
*weakreflist
;
27 PyDoc_STRVAR(iobase_doc
,
28 "The abstract base class for all I/O classes, acting on streams of\n"
29 "bytes. There is no public constructor.\n"
31 "This class provides dummy implementations for many methods that\n"
32 "derived classes can override selectively; the default implementations\n"
33 "represent a file that cannot be read, written or seeked.\n"
35 "Even though IOBase does not declare read, readinto, or write because\n"
36 "their signatures will vary, implementations and clients should\n"
37 "consider those methods part of the interface. Also, implementations\n"
38 "may raise a IOError when operations they do not support are called.\n"
40 "The basic type used for binary data read from or written to a file is\n"
41 "bytes. bytearrays are accepted too, and in some cases (such as\n"
42 "readinto) needed. Text I/O classes work with str data.\n"
44 "Note that calling any method (except additional calls to close(),\n"
45 "which are ignored) on a closed stream should raise a ValueError.\n"
47 "IOBase (and its subclasses) support the iterator protocol, meaning\n"
48 "that an IOBase object can be iterated over yielding the lines in a\n"
51 "IOBase also supports the :keyword:`with` statement. In this example,\n"
52 "fp is closed after the suite of the with statement is complete:\n"
54 "with open('spam.txt', 'r') as fp:\n"
55 " fp.write('Spam and eggs!')\n");
57 /* Use this macro whenever you want to check the internal `closed` status
58 of the IOBase object rather than the virtual `closed` attribute as returned
59 by whatever subclass. */
61 #define IS_CLOSED(self) \
62 PyObject_HasAttrString(self, "__IOBase_closed")
64 /* Internal methods */
66 iobase_unsupported(const char *message
)
68 PyErr_SetString(_PyIO_unsupported_operation
, message
);
74 PyDoc_STRVAR(iobase_seek_doc
,
75 "Change stream position.\n"
77 "Change the stream position to the given byte offset. The offset is\n"
78 "interpreted relative to the position indicated by whence. Values\n"
81 "* 0 -- start of stream (the default); offset should be zero or positive\n"
82 "* 1 -- current stream position; offset may be negative\n"
83 "* 2 -- end of stream; offset is usually negative\n"
85 "Return the new absolute position.");
88 iobase_seek(PyObject
*self
, PyObject
*args
)
90 return iobase_unsupported("seek");
93 PyDoc_STRVAR(iobase_tell_doc
,
94 "Return current stream position.");
97 iobase_tell(PyObject
*self
, PyObject
*args
)
99 return PyObject_CallMethod(self
, "seek", "ii", 0, 1);
102 PyDoc_STRVAR(iobase_truncate_doc
,
103 "Truncate file to size bytes.\n"
105 "File pointer is left unchanged. Size defaults to the current IO\n"
106 "position as reported by tell(). Returns the new size.");
109 iobase_truncate(PyObject
*self
, PyObject
*args
)
111 return iobase_unsupported("truncate");
114 /* Flush and close methods */
116 PyDoc_STRVAR(iobase_flush_doc
,
117 "Flush write buffers, if applicable.\n"
119 "This is not implemented for read-only and non-blocking streams.\n");
122 iobase_flush(PyObject
*self
, PyObject
*args
)
124 /* XXX Should this return the number of bytes written??? */
125 if (IS_CLOSED(self
)) {
126 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed file.");
132 PyDoc_STRVAR(iobase_close_doc
,
133 "Flush and close the IO object.\n"
135 "This method has no effect if the file is already closed.\n");
138 iobase_closed(PyObject
*self
)
142 /* This gets the derived attribute, which is *not* __IOBase_closed
144 res
= PyObject_GetAttr(self
, _PyIO_str_closed
);
147 closed
= PyObject_IsTrue(res
);
153 iobase_closed_get(PyObject
*self
, void *context
)
155 return PyBool_FromLong(IS_CLOSED(self
));
159 _PyIOBase_check_closed(PyObject
*self
, PyObject
*args
)
161 if (iobase_closed(self
)) {
162 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed file.");
171 /* XXX: IOBase thinks it has to maintain its own internal state in
172 `__IOBase_closed` and call flush() by itself, but it is redundant with
173 whatever behaviour a non-trivial derived class will implement. */
176 iobase_close(PyObject
*self
, PyObject
*args
)
183 res
= PyObject_CallMethodObjArgs(self
, _PyIO_str_flush
, NULL
);
184 PyObject_SetAttrString(self
, "__IOBase_closed", Py_True
);
192 /* Finalization and garbage collection support */
195 _PyIOBase_finalize(PyObject
*self
)
198 PyObject
*tp
, *v
, *tb
;
202 /* If _PyIOBase_finalize() is called from a destructor, we need to
203 resurrect the object as calling close() can invoke arbitrary code. */
204 is_zombie
= (Py_REFCNT(self
) == 0);
208 PyErr_Fetch(&tp
, &v
, &tb
);
209 /* If `closed` doesn't exist or can't be evaluated as bool, then the
210 object is probably in an unusable state, so ignore. */
211 res
= PyObject_GetAttr(self
, _PyIO_str_closed
);
215 closed
= PyObject_IsTrue(res
);
221 res
= PyObject_CallMethodObjArgs((PyObject
*) self
, _PyIO_str_close
,
223 /* Silencing I/O errors is bad, but printing spurious tracebacks is
224 equally as bad, and potentially more frequent (because of
231 PyErr_Restore(tp
, v
, tb
);
233 if (--Py_REFCNT(self
) != 0) {
234 /* The object lives again. The following code is taken from
235 slot_tp_del in typeobject.c. */
236 Py_ssize_t refcnt
= Py_REFCNT(self
);
237 _Py_NewReference(self
);
238 Py_REFCNT(self
) = refcnt
;
239 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
240 * we need to undo that. */
242 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
243 * chain, so no more to do there.
244 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
245 * _Py_NewReference bumped tp_allocs: both of those need to be
249 --Py_TYPE(self
)->tp_frees
;
250 --Py_TYPE(self
)->tp_allocs
;
259 iobase_traverse(iobase
*self
, visitproc visit
, void *arg
)
261 Py_VISIT(self
->dict
);
266 iobase_clear(iobase
*self
)
268 if (_PyIOBase_finalize((PyObject
*) self
) < 0)
270 Py_CLEAR(self
->dict
);
277 iobase_dealloc(iobase
*self
)
279 /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
280 are still available here for close() to use.
281 However, if the derived class declares a __slots__, those slots are
284 if (_PyIOBase_finalize((PyObject
*) self
) < 0) {
285 /* When called from a heap type's dealloc, the type will be
286 decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
287 if (PyType_HasFeature(Py_TYPE(self
), Py_TPFLAGS_HEAPTYPE
))
288 Py_INCREF(Py_TYPE(self
));
291 _PyObject_GC_UNTRACK(self
);
292 if (self
->weakreflist
!= NULL
)
293 PyObject_ClearWeakRefs((PyObject
*) self
);
294 Py_CLEAR(self
->dict
);
295 Py_TYPE(self
)->tp_free((PyObject
*) self
);
298 /* Inquiry methods */
300 PyDoc_STRVAR(iobase_seekable_doc
,
301 "Return whether object supports random access.\n"
303 "If False, seek(), tell() and truncate() will raise IOError.\n"
304 "This method may need to do a test seek().");
307 iobase_seekable(PyObject
*self
, PyObject
*args
)
313 _PyIOBase_check_seekable(PyObject
*self
, PyObject
*args
)
315 PyObject
*res
= PyObject_CallMethodObjArgs(self
, _PyIO_str_seekable
, NULL
);
318 if (res
!= Py_True
) {
320 PyErr_SetString(PyExc_IOError
, "File or stream is not seekable.");
323 if (args
== Py_True
) {
329 PyDoc_STRVAR(iobase_readable_doc
,
330 "Return whether object was opened for reading.\n"
332 "If False, read() will raise IOError.");
335 iobase_readable(PyObject
*self
, PyObject
*args
)
340 /* May be called with any object */
342 _PyIOBase_check_readable(PyObject
*self
, PyObject
*args
)
344 PyObject
*res
= PyObject_CallMethodObjArgs(self
, _PyIO_str_readable
, NULL
);
347 if (res
!= Py_True
) {
349 PyErr_SetString(PyExc_IOError
, "File or stream is not readable.");
352 if (args
== Py_True
) {
358 PyDoc_STRVAR(iobase_writable_doc
,
359 "Return whether object was opened for writing.\n"
361 "If False, read() will raise IOError.");
364 iobase_writable(PyObject
*self
, PyObject
*args
)
369 /* May be called with any object */
371 _PyIOBase_check_writable(PyObject
*self
, PyObject
*args
)
373 PyObject
*res
= PyObject_CallMethodObjArgs(self
, _PyIO_str_writable
, NULL
);
376 if (res
!= Py_True
) {
378 PyErr_SetString(PyExc_IOError
, "File or stream is not writable.");
381 if (args
== Py_True
) {
387 /* Context manager */
390 iobase_enter(PyObject
*self
, PyObject
*args
)
392 if (_PyIOBase_check_closed(self
, Py_True
) == NULL
)
400 iobase_exit(PyObject
*self
, PyObject
*args
)
402 return PyObject_CallMethodObjArgs(self
, _PyIO_str_close
, NULL
);
405 /* Lower-level APIs */
407 /* XXX Should these be present even if unimplemented? */
409 PyDoc_STRVAR(iobase_fileno_doc
,
410 "Returns underlying file descriptor if one exists.\n"
412 "An IOError is raised if the IO object does not use a file descriptor.\n");
415 iobase_fileno(PyObject
*self
, PyObject
*args
)
417 return iobase_unsupported("fileno");
420 PyDoc_STRVAR(iobase_isatty_doc
,
421 "Return whether this is an 'interactive' stream.\n"
423 "Return False if it can't be determined.\n");
426 iobase_isatty(PyObject
*self
, PyObject
*args
)
428 if (_PyIOBase_check_closed(self
, Py_True
) == NULL
)
433 /* Readline(s) and writelines */
435 PyDoc_STRVAR(iobase_readline_doc
,
436 "Read and return a line from the stream.\n"
438 "If limit is specified, at most limit bytes will be read.\n"
440 "The line terminator is always b'\\n' for binary files; for text\n"
441 "files, the newlines argument to open can be used to select the line\n"
442 "terminator(s) recognized.\n");
445 iobase_readline(PyObject
*self
, PyObject
*args
)
447 /* For backwards compatibility, a (slowish) readline(). */
449 Py_ssize_t limit
= -1;
451 PyObject
*buffer
, *result
;
452 Py_ssize_t old_size
= -1;
454 if (!PyArg_ParseTuple(args
, "|O&:readline", &_PyIO_ConvertSsize_t
, &limit
)) {
458 if (PyObject_HasAttrString(self
, "peek"))
461 buffer
= PyByteArray_FromStringAndSize(NULL
, 0);
465 while (limit
< 0 || Py_SIZE(buffer
) < limit
) {
466 Py_ssize_t nreadahead
= 1;
470 PyObject
*readahead
= PyObject_CallMethod(self
, "peek", "i", 1);
471 if (readahead
== NULL
) {
472 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
473 when EINTR occurs so we needn't do it ourselves. */
474 if (_PyIO_trap_eintr()) {
479 if (!PyBytes_Check(readahead
)) {
480 PyErr_Format(PyExc_IOError
,
481 "peek() should have returned a bytes object, "
482 "not '%.200s'", Py_TYPE(readahead
)->tp_name
);
483 Py_DECREF(readahead
);
486 if (PyBytes_GET_SIZE(readahead
) > 0) {
488 const char *buf
= PyBytes_AS_STRING(readahead
);
491 if (n
>= PyBytes_GET_SIZE(readahead
) || n
>= limit
)
493 if (buf
[n
++] == '\n')
499 if (n
>= PyBytes_GET_SIZE(readahead
))
501 if (buf
[n
++] == '\n')
507 Py_DECREF(readahead
);
510 b
= PyObject_CallMethod(self
, "read", "n", nreadahead
);
512 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
513 when EINTR occurs so we needn't do it ourselves. */
514 if (_PyIO_trap_eintr()) {
519 if (!PyBytes_Check(b
)) {
520 PyErr_Format(PyExc_IOError
,
521 "read() should have returned a bytes object, "
522 "not '%.200s'", Py_TYPE(b
)->tp_name
);
526 if (PyBytes_GET_SIZE(b
) == 0) {
531 old_size
= PyByteArray_GET_SIZE(buffer
);
532 PyByteArray_Resize(buffer
, old_size
+ PyBytes_GET_SIZE(b
));
533 memcpy(PyByteArray_AS_STRING(buffer
) + old_size
,
534 PyBytes_AS_STRING(b
), PyBytes_GET_SIZE(b
));
538 if (PyByteArray_AS_STRING(buffer
)[PyByteArray_GET_SIZE(buffer
) - 1] == '\n')
542 result
= PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer
),
543 PyByteArray_GET_SIZE(buffer
));
552 iobase_iter(PyObject
*self
)
554 if (_PyIOBase_check_closed(self
, Py_True
) == NULL
)
562 iobase_iternext(PyObject
*self
)
564 PyObject
*line
= PyObject_CallMethodObjArgs(self
, _PyIO_str_readline
, NULL
);
569 if (PyObject_Size(line
) == 0) {
577 PyDoc_STRVAR(iobase_readlines_doc
,
578 "Return a list of lines from the stream.\n"
580 "hint can be specified to control the number of lines read: no more\n"
581 "lines will be read if the total size (in bytes/characters) of all\n"
582 "lines so far exceeds hint.");
585 iobase_readlines(PyObject
*self
, PyObject
*args
)
587 Py_ssize_t hint
= -1, length
= 0;
590 if (!PyArg_ParseTuple(args
, "|O&:readlines", &_PyIO_ConvertSsize_t
, &hint
)) {
594 result
= PyList_New(0);
599 /* XXX special-casing this made sense in the Python version in order
600 to remove the bytecode interpretation overhead, but it could
601 probably be removed here. */
602 PyObject
*ret
= PyObject_CallMethod(result
, "extend", "O", self
);
612 PyObject
*line
= PyIter_Next(self
);
614 if (PyErr_Occurred()) {
619 break; /* StopIteration raised */
622 if (PyList_Append(result
, line
) < 0) {
627 length
+= PyObject_Size(line
);
637 iobase_writelines(PyObject
*self
, PyObject
*args
)
639 PyObject
*lines
, *iter
, *res
;
641 if (!PyArg_ParseTuple(args
, "O:writelines", &lines
)) {
645 if (_PyIOBase_check_closed(self
, Py_True
) == NULL
)
648 iter
= PyObject_GetIter(lines
);
653 PyObject
*line
= PyIter_Next(iter
);
655 if (PyErr_Occurred()) {
660 break; /* Stop Iteration */
665 res
= PyObject_CallMethodObjArgs(self
, _PyIO_str_write
, line
, NULL
);
666 } while (res
== NULL
&& _PyIO_trap_eintr());
678 static PyMethodDef iobase_methods
[] = {
679 {"seek", iobase_seek
, METH_VARARGS
, iobase_seek_doc
},
680 {"tell", iobase_tell
, METH_NOARGS
, iobase_tell_doc
},
681 {"truncate", iobase_truncate
, METH_VARARGS
, iobase_truncate_doc
},
682 {"flush", iobase_flush
, METH_NOARGS
, iobase_flush_doc
},
683 {"close", iobase_close
, METH_NOARGS
, iobase_close_doc
},
685 {"seekable", iobase_seekable
, METH_NOARGS
, iobase_seekable_doc
},
686 {"readable", iobase_readable
, METH_NOARGS
, iobase_readable_doc
},
687 {"writable", iobase_writable
, METH_NOARGS
, iobase_writable_doc
},
689 {"_checkClosed", _PyIOBase_check_closed
, METH_NOARGS
},
690 {"_checkSeekable", _PyIOBase_check_seekable
, METH_NOARGS
},
691 {"_checkReadable", _PyIOBase_check_readable
, METH_NOARGS
},
692 {"_checkWritable", _PyIOBase_check_writable
, METH_NOARGS
},
694 {"fileno", iobase_fileno
, METH_NOARGS
, iobase_fileno_doc
},
695 {"isatty", iobase_isatty
, METH_NOARGS
, iobase_isatty_doc
},
697 {"__enter__", iobase_enter
, METH_NOARGS
},
698 {"__exit__", iobase_exit
, METH_VARARGS
},
700 {"readline", iobase_readline
, METH_VARARGS
, iobase_readline_doc
},
701 {"readlines", iobase_readlines
, METH_VARARGS
, iobase_readlines_doc
},
702 {"writelines", iobase_writelines
, METH_VARARGS
},
707 static PyGetSetDef iobase_getset
[] = {
708 {"closed", (getter
)iobase_closed_get
, NULL
, NULL
},
713 PyTypeObject PyIOBase_Type
= {
714 PyVarObject_HEAD_INIT(NULL
, 0)
715 "_io._IOBase", /*tp_name*/
716 sizeof(iobase
), /*tp_basicsize*/
718 (destructor
)iobase_dealloc
, /*tp_dealloc*/
725 0, /*tp_as_sequence*/
733 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
734 | Py_TPFLAGS_HAVE_GC
, /*tp_flags*/
735 iobase_doc
, /* tp_doc */
736 (traverseproc
)iobase_traverse
, /* tp_traverse */
737 (inquiry
)iobase_clear
, /* tp_clear */
738 0, /* tp_richcompare */
739 offsetof(iobase
, weakreflist
), /* tp_weaklistoffset */
740 iobase_iter
, /* tp_iter */
741 iobase_iternext
, /* tp_iternext */
742 iobase_methods
, /* tp_methods */
744 iobase_getset
, /* tp_getset */
747 0, /* tp_descr_get */
748 0, /* tp_descr_set */
749 offsetof(iobase
, dict
), /* tp_dictoffset */
752 PyType_GenericNew
, /* tp_new */
757 * RawIOBase class, Inherits from IOBase.
759 PyDoc_STRVAR(rawiobase_doc
,
760 "Base class for raw binary I/O.");
763 * The read() method is implemented by calling readinto(); derived classes
764 * that want to support read() only need to implement readinto() as a
765 * primitive operation. In general, readinto() can be more efficient than
768 * (It would be tempting to also provide an implementation of readinto() in
769 * terms of read(), in case the latter is a more suitable primitive operation,
770 * but that would lead to nasty recursion in case a subclass doesn't implement
775 rawiobase_read(PyObject
*self
, PyObject
*args
)
780 if (!PyArg_ParseTuple(args
, "|n:read", &n
)) {
785 return PyObject_CallMethod(self
, "readall", NULL
);
787 /* TODO: allocate a bytes object directly instead and manually construct
788 a writable memoryview pointing to it. */
789 b
= PyByteArray_FromStringAndSize(NULL
, n
);
793 res
= PyObject_CallMethodObjArgs(self
, _PyIO_str_readinto
, b
, NULL
);
794 if (res
== NULL
|| res
== Py_None
) {
799 n
= PyNumber_AsSsize_t(res
, PyExc_ValueError
);
801 if (n
== -1 && PyErr_Occurred()) {
806 res
= PyBytes_FromStringAndSize(PyByteArray_AsString(b
), n
);
812 PyDoc_STRVAR(rawiobase_readall_doc
,
813 "Read until EOF, using multiple read() call.");
816 rawiobase_readall(PyObject
*self
, PyObject
*args
)
819 PyObject
*chunks
= PyList_New(0);
826 PyObject
*data
= PyObject_CallMethod(self
, "read",
827 "i", DEFAULT_BUFFER_SIZE
);
829 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
830 when EINTR occurs so we needn't do it ourselves. */
831 if (_PyIO_trap_eintr()) {
837 if (data
== Py_None
) {
838 if (PyList_GET_SIZE(chunks
) == 0) {
845 if (!PyBytes_Check(data
)) {
848 PyErr_SetString(PyExc_TypeError
, "read() should return bytes");
851 if (PyBytes_GET_SIZE(data
) == 0) {
856 r
= PyList_Append(chunks
, data
);
863 result
= _PyBytes_Join(_PyIO_empty_bytes
, chunks
);
868 static PyMethodDef rawiobase_methods
[] = {
869 {"read", rawiobase_read
, METH_VARARGS
},
870 {"readall", rawiobase_readall
, METH_NOARGS
, rawiobase_readall_doc
},
874 PyTypeObject PyRawIOBase_Type
= {
875 PyVarObject_HEAD_INIT(NULL
, 0)
876 "_io._RawIOBase", /*tp_name*/
886 0, /*tp_as_sequence*/
894 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
895 rawiobase_doc
, /* tp_doc */
898 0, /* tp_richcompare */
899 0, /* tp_weaklistoffset */
902 rawiobase_methods
, /* tp_methods */
905 &PyIOBase_Type
, /* tp_base */
907 0, /* tp_descr_get */
908 0, /* tp_descr_set */
909 0, /* tp_dictoffset */