blob: a8d3ed4354b6af5c4ebdd26493004aba96fe4d03 [file] [log] [blame]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001/*
2 An implementation of the new I/O lib as defined by PEP 3116 - "New I/O"
3
4 Classes defined here: UnsupportedOperation, BlockingIOError.
5 Functions defined here: open().
6
7 Mostly written by Amaury Forgeot d'Arc
8*/
9
10#define PY_SSIZE_T_CLEAN
11#include "Python.h"
12#include "structmember.h"
13#include "_iomodule.h"
14
15#ifdef HAVE_SYS_TYPES_H
16#include <sys/types.h>
17#endif /* HAVE_SYS_TYPES_H */
18
19#ifdef HAVE_SYS_STAT_H
20#include <sys/stat.h>
21#endif /* HAVE_SYS_STAT_H */
22
23
24/* Various interned strings */
25
26PyObject *_PyIO_str_close;
27PyObject *_PyIO_str_closed;
28PyObject *_PyIO_str_decode;
29PyObject *_PyIO_str_encode;
30PyObject *_PyIO_str_fileno;
31PyObject *_PyIO_str_flush;
32PyObject *_PyIO_str_getstate;
33PyObject *_PyIO_str_isatty;
34PyObject *_PyIO_str_newlines;
35PyObject *_PyIO_str_nl;
36PyObject *_PyIO_str_read;
37PyObject *_PyIO_str_read1;
38PyObject *_PyIO_str_readable;
Victor Stinnerb57f1082011-05-26 00:19:38 +020039PyObject *_PyIO_str_readall;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000040PyObject *_PyIO_str_readinto;
41PyObject *_PyIO_str_readline;
42PyObject *_PyIO_str_reset;
43PyObject *_PyIO_str_seek;
44PyObject *_PyIO_str_seekable;
Antoine Pitroue4501852009-05-14 18:55:55 +000045PyObject *_PyIO_str_setstate;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000046PyObject *_PyIO_str_tell;
47PyObject *_PyIO_str_truncate;
48PyObject *_PyIO_str_writable;
49PyObject *_PyIO_str_write;
50
51PyObject *_PyIO_empty_str;
52PyObject *_PyIO_empty_bytes;
Antoine Pitroue4501852009-05-14 18:55:55 +000053PyObject *_PyIO_zero;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000054
55
56PyDoc_STRVAR(module_doc,
57"The io module provides the Python interfaces to stream handling. The\n"
58"builtin open function is defined in this module.\n"
59"\n"
60"At the top of the I/O hierarchy is the abstract base class IOBase. It\n"
61"defines the basic interface to a stream. Note, however, that there is no\n"
62"seperation between reading and writing to streams; implementations are\n"
63"allowed to throw an IOError if they do not support a given operation.\n"
64"\n"
65"Extending IOBase is RawIOBase which deals simply with the reading and\n"
Benjamin Peterson8f2b6652009-04-05 00:46:27 +000066"writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000067"an interface to OS files.\n"
68"\n"
69"BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its\n"
70"subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer\n"
71"streams that are readable, writable, and both respectively.\n"
72"BufferedRandom provides a buffered interface to random access\n"
73"streams. BytesIO is a simple stream of in-memory bytes.\n"
74"\n"
75"Another IOBase subclass, TextIOBase, deals with the encoding and decoding\n"
76"of streams into text. TextIOWrapper, which extends it, is a buffered text\n"
77"interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO\n"
78"is a in-memory stream for text.\n"
79"\n"
80"Argument names are not part of the specification, and only the arguments\n"
81"of open() are intended to be used as keyword arguments.\n"
82"\n"
83"data:\n"
84"\n"
85"DEFAULT_BUFFER_SIZE\n"
86"\n"
87" An int containing the default buffer size used by the module's buffered\n"
88" I/O classes. open() uses the file's blksize (as obtained by os.stat) if\n"
89" possible.\n"
90 );
91
92
93/*
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000094 * The main open() function
95 */
96PyDoc_STRVAR(open_doc,
Georg Brandle40ee502010-07-11 09:33:39 +000097"open(file, mode='r', buffering=-1, encoding=None,\n"
Ross Lagerwall59142db2011-10-31 20:34:46 +020098" errors=None, newline=None, closefd=True, opener=None) -> file object\n"
Georg Brandl5e8f6d12009-12-23 10:30:45 +000099"\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000100"Open file and return a stream. Raise IOError upon failure.\n"
101"\n"
102"file is either a text or byte string giving the name (and the path\n"
103"if the file isn't in the current working directory) of the file to\n"
104"be opened or an integer file descriptor of the file to be\n"
105"wrapped. (If a file descriptor is given, it is closed when the\n"
106"returned I/O object is closed, unless closefd is set to False.)\n"
107"\n"
108"mode is an optional string that specifies the mode in which the file\n"
109"is opened. It defaults to 'r' which means open for reading in text\n"
110"mode. Other common values are 'w' for writing (truncating the file if\n"
111"it already exists), and 'a' for appending (which on some Unix systems,\n"
112"means that all writes append to the end of the file regardless of the\n"
113"current seek position). In text mode, if encoding is not specified the\n"
114"encoding used is platform dependent. (For reading and writing raw\n"
115"bytes use binary mode and leave encoding unspecified.) The available\n"
116"modes are:\n"
117"\n"
118"========= ===============================================================\n"
119"Character Meaning\n"
120"--------- ---------------------------------------------------------------\n"
121"'r' open for reading (default)\n"
122"'w' open for writing, truncating the file first\n"
123"'a' open for writing, appending to the end of the file if it exists\n"
124"'b' binary mode\n"
125"'t' text mode (default)\n"
126"'+' open a disk file for updating (reading and writing)\n"
127"'U' universal newline mode (for backwards compatibility; unneeded\n"
128" for new code)\n"
129"========= ===============================================================\n"
130"\n"
131"The default mode is 'rt' (open for reading text). For binary random\n"
132"access, the mode 'w+b' opens and truncates the file to 0 bytes, while\n"
133"'r+b' opens the file without truncation.\n"
134"\n"
135"Python distinguishes between files opened in binary and text modes,\n"
136"even when the underlying operating system doesn't. Files opened in\n"
137"binary mode (appending 'b' to the mode argument) return contents as\n"
138"bytes objects without any decoding. In text mode (the default, or when\n"
139"'t' is appended to the mode argument), the contents of the file are\n"
140"returned as strings, the bytes having been first decoded using a\n"
141"platform-dependent encoding or using the specified encoding if given.\n"
142"\n"
Antoine Pitroud5587bc2009-12-19 21:08:31 +0000143"buffering is an optional integer used to set the buffering policy.\n"
144"Pass 0 to switch buffering off (only allowed in binary mode), 1 to select\n"
145"line buffering (only usable in text mode), and an integer > 1 to indicate\n"
146"the size of a fixed-size chunk buffer. When no buffering argument is\n"
147"given, the default buffering policy works as follows:\n"
148"\n"
149"* Binary files are buffered in fixed-size chunks; the size of the buffer\n"
150" is chosen using a heuristic trying to determine the underlying device's\n"
151" \"block size\" and falling back on `io.DEFAULT_BUFFER_SIZE`.\n"
152" On many systems, the buffer will typically be 4096 or 8192 bytes long.\n"
153"\n"
154"* \"Interactive\" text files (files for which isatty() returns True)\n"
155" use line buffering. Other text files use the policy described above\n"
156" for binary files.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000157"\n"
158"encoding is the name of the encoding used to decode or encode the\n"
159"file. This should only be used in text mode. The default encoding is\n"
160"platform dependent, but any encoding supported by Python can be\n"
161"passed. See the codecs module for the list of supported encodings.\n"
162"\n"
163"errors is an optional string that specifies how encoding errors are to\n"
164"be handled---this argument should not be used in binary mode. Pass\n"
165"'strict' to raise a ValueError exception if there is an encoding error\n"
166"(the default of None has the same effect), or pass 'ignore' to ignore\n"
167"errors. (Note that ignoring encoding errors can lead to data loss.)\n"
168"See the documentation for codecs.register for a list of the permitted\n"
169"encoding error strings.\n"
170"\n"
171"newline controls how universal newlines works (it only applies to text\n"
172"mode). It can be None, '', '\\n', '\\r', and '\\r\\n'. It works as\n"
173"follows:\n"
174"\n"
175"* On input, if newline is None, universal newlines mode is\n"
176" enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and\n"
177" these are translated into '\\n' before being returned to the\n"
178" caller. If it is '', universal newline mode is enabled, but line\n"
179" endings are returned to the caller untranslated. If it has any of\n"
180" the other legal values, input lines are only terminated by the given\n"
181" string, and the line ending is returned to the caller untranslated.\n"
182"\n"
183"* On output, if newline is None, any '\\n' characters written are\n"
184" translated to the system default line separator, os.linesep. If\n"
185" newline is '', no translation takes place. If newline is any of the\n"
186" other legal values, any '\\n' characters written are translated to\n"
187" the given string.\n"
188"\n"
189"If closefd is False, the underlying file descriptor will be kept open\n"
190"when the file is closed. This does not work when a file name is given\n"
191"and must be True in that case.\n"
192"\n"
Ross Lagerwall59142db2011-10-31 20:34:46 +0200193"A custom opener can be used by passing a callable as *opener*. The\n"
194"underlying file descriptor for the file object is then obtained by\n"
195"calling *opener* with (*file*, *flags*). *opener* must return an open\n"
196"file descriptor (passing os.open as *opener* results in functionality\n"
197"similar to passing None).\n"
198"\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000199"open() returns a file object whose type depends on the mode, and\n"
200"through which the standard file operations such as reading and writing\n"
201"are performed. When open() is used to open a file in a text mode ('w',\n"
202"'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open\n"
203"a file in a binary mode, the returned class varies: in read binary\n"
204"mode, it returns a BufferedReader; in write binary and append binary\n"
205"modes, it returns a BufferedWriter, and in read/write mode, it returns\n"
206"a BufferedRandom.\n"
207"\n"
208"It is also possible to use a string or bytearray as a file for both\n"
209"reading and writing. For strings StringIO can be used like a file\n"
210"opened in a text mode, and for bytes a BytesIO can be used like a file\n"
211"opened in a binary mode.\n"
212 );
213
214static PyObject *
215io_open(PyObject *self, PyObject *args, PyObject *kwds)
216{
217 char *kwlist[] = {"file", "mode", "buffering",
218 "encoding", "errors", "newline",
Ross Lagerwall59142db2011-10-31 20:34:46 +0200219 "closefd", "opener", NULL};
220 PyObject *file, *opener = Py_None;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000221 char *mode = "r";
222 int buffering = -1, closefd = 1;
223 char *encoding = NULL, *errors = NULL, *newline = NULL;
224 unsigned i;
225
226 int reading = 0, writing = 0, appending = 0, updating = 0;
227 int text = 0, binary = 0, universal = 0;
228
229 char rawmode[5], *m;
230 int line_buffering, isatty;
231
232 PyObject *raw, *modeobj = NULL, *buffer = NULL, *wrapper = NULL;
233
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200234 _Py_IDENTIFIER(isatty);
235 _Py_IDENTIFIER(fileno);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200236
Ross Lagerwall59142db2011-10-31 20:34:46 +0200237 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|sizzziO:open", kwlist,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000238 &file, &mode, &buffering,
239 &encoding, &errors, &newline,
Ross Lagerwall59142db2011-10-31 20:34:46 +0200240 &closefd, &opener)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000241 return NULL;
242 }
243
244 if (!PyUnicode_Check(file) &&
245 !PyBytes_Check(file) &&
246 !PyNumber_Check(file)) {
247 PyErr_Format(PyExc_TypeError, "invalid file: %R", file);
248 return NULL;
249 }
250
251 /* Decode mode */
252 for (i = 0; i < strlen(mode); i++) {
253 char c = mode[i];
254
255 switch (c) {
256 case 'r':
257 reading = 1;
258 break;
259 case 'w':
260 writing = 1;
261 break;
262 case 'a':
263 appending = 1;
264 break;
265 case '+':
266 updating = 1;
267 break;
268 case 't':
269 text = 1;
270 break;
271 case 'b':
272 binary = 1;
273 break;
274 case 'U':
275 universal = 1;
276 reading = 1;
277 break;
278 default:
279 goto invalid_mode;
280 }
281
282 /* c must not be duplicated */
283 if (strchr(mode+i+1, c)) {
284 invalid_mode:
285 PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode);
286 return NULL;
287 }
288
289 }
290
291 m = rawmode;
292 if (reading) *(m++) = 'r';
293 if (writing) *(m++) = 'w';
294 if (appending) *(m++) = 'a';
295 if (updating) *(m++) = '+';
296 *m = '\0';
297
298 /* Parameters validation */
299 if (universal) {
300 if (writing || appending) {
301 PyErr_SetString(PyExc_ValueError,
302 "can't use U and writing mode at once");
303 return NULL;
304 }
305 reading = 1;
306 }
307
308 if (text && binary) {
309 PyErr_SetString(PyExc_ValueError,
310 "can't have text and binary mode at once");
311 return NULL;
312 }
313
314 if (reading + writing + appending > 1) {
315 PyErr_SetString(PyExc_ValueError,
316 "must have exactly one of read/write/append mode");
317 return NULL;
318 }
319
320 if (binary && encoding != NULL) {
321 PyErr_SetString(PyExc_ValueError,
322 "binary mode doesn't take an encoding argument");
323 return NULL;
324 }
325
326 if (binary && errors != NULL) {
327 PyErr_SetString(PyExc_ValueError,
328 "binary mode doesn't take an errors argument");
329 return NULL;
330 }
331
332 if (binary && newline != NULL) {
333 PyErr_SetString(PyExc_ValueError,
334 "binary mode doesn't take a newline argument");
335 return NULL;
336 }
337
338 /* Create the Raw file stream */
339 raw = PyObject_CallFunction((PyObject *)&PyFileIO_Type,
Ross Lagerwall59142db2011-10-31 20:34:46 +0200340 "OsiO", file, rawmode, closefd, opener);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000341 if (raw == NULL)
342 return NULL;
343
344 modeobj = PyUnicode_FromString(mode);
345 if (modeobj == NULL)
346 goto error;
347
348 /* buffering */
349 {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200350 PyObject *res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000351 if (res == NULL)
352 goto error;
353 isatty = PyLong_AsLong(res);
354 Py_DECREF(res);
355 if (isatty == -1 && PyErr_Occurred())
356 goto error;
357 }
358
359 if (buffering == 1 || (buffering < 0 && isatty)) {
360 buffering = -1;
361 line_buffering = 1;
362 }
363 else
364 line_buffering = 0;
365
366 if (buffering < 0) {
367 buffering = DEFAULT_BUFFER_SIZE;
368#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
369 {
370 struct stat st;
371 long fileno;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200372 PyObject *res = _PyObject_CallMethodId(raw, &PyId_fileno, NULL);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000373 if (res == NULL)
374 goto error;
375
376 fileno = PyLong_AsLong(res);
377 Py_DECREF(res);
378 if (fileno == -1 && PyErr_Occurred())
379 goto error;
380
Antoine Pitrouea5d17d2010-10-27 19:45:43 +0000381 if (fstat(fileno, &st) >= 0 && st.st_blksize > 1)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000382 buffering = st.st_blksize;
383 }
384#endif
385 }
386 if (buffering < 0) {
387 PyErr_SetString(PyExc_ValueError,
388 "invalid buffering size");
389 goto error;
390 }
391
392 /* if not buffering, returns the raw file object */
393 if (buffering == 0) {
394 if (!binary) {
395 PyErr_SetString(PyExc_ValueError,
396 "can't have unbuffered text I/O");
397 goto error;
398 }
399
400 Py_DECREF(modeobj);
401 return raw;
402 }
403
404 /* wraps into a buffered file */
405 {
406 PyObject *Buffered_class;
407
408 if (updating)
409 Buffered_class = (PyObject *)&PyBufferedRandom_Type;
410 else if (writing || appending)
411 Buffered_class = (PyObject *)&PyBufferedWriter_Type;
412 else if (reading)
413 Buffered_class = (PyObject *)&PyBufferedReader_Type;
414 else {
415 PyErr_Format(PyExc_ValueError,
416 "unknown mode: '%s'", mode);
417 goto error;
418 }
419
420 buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering);
421 }
422 Py_CLEAR(raw);
423 if (buffer == NULL)
424 goto error;
425
426
427 /* if binary, returns the buffered file */
428 if (binary) {
429 Py_DECREF(modeobj);
430 return buffer;
431 }
432
433 /* wraps into a TextIOWrapper */
434 wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type,
435 "Osssi",
436 buffer,
437 encoding, errors, newline,
438 line_buffering);
439 Py_CLEAR(buffer);
440 if (wrapper == NULL)
441 goto error;
442
443 if (PyObject_SetAttrString(wrapper, "mode", modeobj) < 0)
444 goto error;
445 Py_DECREF(modeobj);
446 return wrapper;
447
448 error:
449 Py_XDECREF(raw);
450 Py_XDECREF(modeobj);
451 Py_XDECREF(buffer);
452 Py_XDECREF(wrapper);
453 return NULL;
454}
455
456/*
457 * Private helpers for the io module.
458 */
459
460Py_off_t
461PyNumber_AsOff_t(PyObject *item, PyObject *err)
462{
463 Py_off_t result;
464 PyObject *runerr;
465 PyObject *value = PyNumber_Index(item);
466 if (value == NULL)
467 return -1;
468
469 /* We're done if PyLong_AsSsize_t() returns without error. */
470 result = PyLong_AsOff_t(value);
471 if (result != -1 || !(runerr = PyErr_Occurred()))
472 goto finish;
473
474 /* Error handling code -- only manage OverflowError differently */
475 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
476 goto finish;
477
478 PyErr_Clear();
479 /* If no error-handling desired then the default clipping
480 is sufficient.
481 */
482 if (!err) {
483 assert(PyLong_Check(value));
484 /* Whether or not it is less than or equal to
485 zero is determined by the sign of ob_size
486 */
487 if (_PyLong_Sign(value) < 0)
488 result = PY_OFF_T_MIN;
489 else
490 result = PY_OFF_T_MAX;
491 }
492 else {
493 /* Otherwise replace the error with caller's error object. */
494 PyErr_Format(err,
495 "cannot fit '%.200s' into an offset-sized integer",
496 item->ob_type->tp_name);
497 }
498
499 finish:
500 Py_DECREF(value);
501 return result;
502}
503
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000504
505/* Basically the "n" format code with the ability to turn None into -1. */
506int
507_PyIO_ConvertSsize_t(PyObject *obj, void *result) {
508 Py_ssize_t limit;
509 if (obj == Py_None) {
510 limit = -1;
511 }
512 else if (PyNumber_Check(obj)) {
513 limit = PyNumber_AsSsize_t(obj, PyExc_OverflowError);
514 if (limit == -1 && PyErr_Occurred())
515 return 0;
516 }
517 else {
518 PyErr_Format(PyExc_TypeError,
519 "integer argument expected, got '%.200s'",
520 Py_TYPE(obj)->tp_name);
521 return 0;
522 }
523 *((Py_ssize_t *)result) = limit;
524 return 1;
525}
526
527
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000528static int
529iomodule_traverse(PyObject *mod, visitproc visit, void *arg) {
530 _PyIO_State *state = IO_MOD_STATE(mod);
531 if (!state->initialized)
532 return 0;
533 Py_VISIT(state->os_module);
534 if (state->locale_module != NULL) {
535 Py_VISIT(state->locale_module);
536 }
537 Py_VISIT(state->unsupported_operation);
538 return 0;
539}
540
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000541
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000542static int
543iomodule_clear(PyObject *mod) {
544 _PyIO_State *state = IO_MOD_STATE(mod);
545 if (!state->initialized)
546 return 0;
547 Py_CLEAR(state->os_module);
548 if (state->locale_module != NULL)
549 Py_CLEAR(state->locale_module);
550 Py_CLEAR(state->unsupported_operation);
551 return 0;
552}
553
554static void
555iomodule_free(PyObject *mod) {
556 iomodule_clear(mod);
557}
558
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000559
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000560/*
561 * Module definition
562 */
563
564static PyMethodDef module_methods[] = {
565 {"open", (PyCFunction)io_open, METH_VARARGS|METH_KEYWORDS, open_doc},
566 {NULL, NULL}
567};
568
569struct PyModuleDef _PyIO_Module = {
570 PyModuleDef_HEAD_INIT,
571 "io",
572 module_doc,
573 sizeof(_PyIO_State),
574 module_methods,
575 NULL,
576 iomodule_traverse,
577 iomodule_clear,
578 (freefunc)iomodule_free,
579};
580
581PyMODINIT_FUNC
582PyInit__io(void)
583{
584 PyObject *m = PyModule_Create(&_PyIO_Module);
585 _PyIO_State *state = NULL;
586 if (m == NULL)
587 return NULL;
588 state = IO_MOD_STATE(m);
589 state->initialized = 0;
590
591 /* put os in the module state */
592 state->os_module = PyImport_ImportModule("os");
593 if (state->os_module == NULL)
594 goto fail;
595
596#define ADD_TYPE(type, name) \
597 if (PyType_Ready(type) < 0) \
598 goto fail; \
599 Py_INCREF(type); \
600 if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
601 Py_DECREF(type); \
602 goto fail; \
603 }
604
605 /* DEFAULT_BUFFER_SIZE */
606 if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
607 goto fail;
608
609 /* UnsupportedOperation inherits from ValueError and IOError */
610 state->unsupported_operation = PyObject_CallFunction(
611 (PyObject *)&PyType_Type, "s(OO){}",
612 "UnsupportedOperation", PyExc_ValueError, PyExc_IOError);
613 if (state->unsupported_operation == NULL)
614 goto fail;
615 Py_INCREF(state->unsupported_operation);
616 if (PyModule_AddObject(m, "UnsupportedOperation",
617 state->unsupported_operation) < 0)
618 goto fail;
619
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200620 /* BlockingIOError, for compatibility */
621 Py_INCREF(PyExc_BlockingIOError);
622 if (PyModule_AddObject(m, "BlockingIOError",
623 (PyObject *) PyExc_BlockingIOError) < 0)
624 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000625
626 /* Concrete base types of the IO ABCs.
627 (the ABCs themselves are declared through inheritance in io.py)
628 */
629 ADD_TYPE(&PyIOBase_Type, "_IOBase");
630 ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
631 ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
632 ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");
633
634 /* Implementation of concrete IO objects. */
635 /* FileIO */
636 PyFileIO_Type.tp_base = &PyRawIOBase_Type;
637 ADD_TYPE(&PyFileIO_Type, "FileIO");
638
639 /* BytesIO */
640 PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
641 ADD_TYPE(&PyBytesIO_Type, "BytesIO");
Antoine Pitrou972ee132010-09-06 18:48:21 +0000642 if (PyType_Ready(&_PyBytesIOBuffer_Type) < 0)
643 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000644
645 /* StringIO */
646 PyStringIO_Type.tp_base = &PyTextIOBase_Type;
647 ADD_TYPE(&PyStringIO_Type, "StringIO");
648
649 /* BufferedReader */
650 PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
651 ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");
652
653 /* BufferedWriter */
654 PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
655 ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");
656
657 /* BufferedRWPair */
658 PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
659 ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");
660
661 /* BufferedRandom */
662 PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
663 ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");
664
665 /* TextIOWrapper */
666 PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
667 ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");
668
669 /* IncrementalNewlineDecoder */
670 ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");
671
672 /* Interned strings */
673 if (!(_PyIO_str_close = PyUnicode_InternFromString("close")))
674 goto fail;
675 if (!(_PyIO_str_closed = PyUnicode_InternFromString("closed")))
676 goto fail;
677 if (!(_PyIO_str_decode = PyUnicode_InternFromString("decode")))
678 goto fail;
679 if (!(_PyIO_str_encode = PyUnicode_InternFromString("encode")))
680 goto fail;
681 if (!(_PyIO_str_fileno = PyUnicode_InternFromString("fileno")))
682 goto fail;
683 if (!(_PyIO_str_flush = PyUnicode_InternFromString("flush")))
684 goto fail;
685 if (!(_PyIO_str_getstate = PyUnicode_InternFromString("getstate")))
686 goto fail;
687 if (!(_PyIO_str_isatty = PyUnicode_InternFromString("isatty")))
688 goto fail;
689 if (!(_PyIO_str_newlines = PyUnicode_InternFromString("newlines")))
690 goto fail;
691 if (!(_PyIO_str_nl = PyUnicode_InternFromString("\n")))
692 goto fail;
693 if (!(_PyIO_str_read = PyUnicode_InternFromString("read")))
694 goto fail;
695 if (!(_PyIO_str_read1 = PyUnicode_InternFromString("read1")))
696 goto fail;
697 if (!(_PyIO_str_readable = PyUnicode_InternFromString("readable")))
698 goto fail;
Victor Stinnerb57f1082011-05-26 00:19:38 +0200699 if (!(_PyIO_str_readall = PyUnicode_InternFromString("readall")))
700 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000701 if (!(_PyIO_str_readinto = PyUnicode_InternFromString("readinto")))
702 goto fail;
703 if (!(_PyIO_str_readline = PyUnicode_InternFromString("readline")))
704 goto fail;
705 if (!(_PyIO_str_reset = PyUnicode_InternFromString("reset")))
706 goto fail;
707 if (!(_PyIO_str_seek = PyUnicode_InternFromString("seek")))
708 goto fail;
709 if (!(_PyIO_str_seekable = PyUnicode_InternFromString("seekable")))
710 goto fail;
Antoine Pitroue4501852009-05-14 18:55:55 +0000711 if (!(_PyIO_str_setstate = PyUnicode_InternFromString("setstate")))
712 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000713 if (!(_PyIO_str_tell = PyUnicode_InternFromString("tell")))
714 goto fail;
715 if (!(_PyIO_str_truncate = PyUnicode_InternFromString("truncate")))
716 goto fail;
717 if (!(_PyIO_str_write = PyUnicode_InternFromString("write")))
718 goto fail;
719 if (!(_PyIO_str_writable = PyUnicode_InternFromString("writable")))
720 goto fail;
721
722 if (!(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
723 goto fail;
724 if (!(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
725 goto fail;
Antoine Pitroue4501852009-05-14 18:55:55 +0000726 if (!(_PyIO_zero = PyLong_FromLong(0L)))
727 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000728
729 state->initialized = 1;
730
731 return m;
732
733 fail:
734 Py_XDECREF(state->os_module);
735 Py_XDECREF(state->unsupported_operation);
736 Py_DECREF(m);
737 return NULL;
738}