blob: dfd66aa7355825ae1988121a77df946daf8e8c0b [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;
39PyObject *_PyIO_str_readinto;
40PyObject *_PyIO_str_readline;
41PyObject *_PyIO_str_reset;
42PyObject *_PyIO_str_seek;
43PyObject *_PyIO_str_seekable;
Antoine Pitroue4501852009-05-14 18:55:55 +000044PyObject *_PyIO_str_setstate;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000045PyObject *_PyIO_str_tell;
46PyObject *_PyIO_str_truncate;
47PyObject *_PyIO_str_writable;
48PyObject *_PyIO_str_write;
49
50PyObject *_PyIO_empty_str;
51PyObject *_PyIO_empty_bytes;
Antoine Pitroue4501852009-05-14 18:55:55 +000052PyObject *_PyIO_zero;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000053
54
55PyDoc_STRVAR(module_doc,
56"The io module provides the Python interfaces to stream handling. The\n"
57"builtin open function is defined in this module.\n"
58"\n"
59"At the top of the I/O hierarchy is the abstract base class IOBase. It\n"
60"defines the basic interface to a stream. Note, however, that there is no\n"
61"seperation between reading and writing to streams; implementations are\n"
62"allowed to throw an IOError if they do not support a given operation.\n"
63"\n"
64"Extending IOBase is RawIOBase which deals simply with the reading and\n"
Benjamin Peterson8f2b6652009-04-05 00:46:27 +000065"writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000066"an interface to OS files.\n"
67"\n"
68"BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its\n"
69"subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer\n"
70"streams that are readable, writable, and both respectively.\n"
71"BufferedRandom provides a buffered interface to random access\n"
72"streams. BytesIO is a simple stream of in-memory bytes.\n"
73"\n"
74"Another IOBase subclass, TextIOBase, deals with the encoding and decoding\n"
75"of streams into text. TextIOWrapper, which extends it, is a buffered text\n"
76"interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO\n"
77"is a in-memory stream for text.\n"
78"\n"
79"Argument names are not part of the specification, and only the arguments\n"
80"of open() are intended to be used as keyword arguments.\n"
81"\n"
82"data:\n"
83"\n"
84"DEFAULT_BUFFER_SIZE\n"
85"\n"
86" An int containing the default buffer size used by the module's buffered\n"
87" I/O classes. open() uses the file's blksize (as obtained by os.stat) if\n"
88" possible.\n"
89 );
90
91
92/*
93 * BlockingIOError extends IOError
94 */
95
96static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000097blockingioerror_init(PyBlockingIOErrorObject *self, PyObject *args,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000098 PyObject *kwds)
99{
100 PyObject *myerrno = NULL, *strerror = NULL;
101 PyObject *baseargs = NULL;
102 Py_ssize_t written = 0;
103
104 assert(PyTuple_Check(args));
105
106 self->written = 0;
107 if (!PyArg_ParseTuple(args, "OO|n:BlockingIOError",
108 &myerrno, &strerror, &written))
109 return -1;
110
111 baseargs = PyTuple_Pack(2, myerrno, strerror);
112 if (baseargs == NULL)
113 return -1;
114 /* This will take care of initializing of myerrno and strerror members */
115 if (((PyTypeObject *)PyExc_IOError)->tp_init(
116 (PyObject *)self, baseargs, kwds) == -1) {
117 Py_DECREF(baseargs);
118 return -1;
119 }
120 Py_DECREF(baseargs);
121
122 self->written = written;
123 return 0;
124}
125
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000126static PyMemberDef blockingioerror_members[] = {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000127 {"characters_written", T_PYSSIZET, offsetof(PyBlockingIOErrorObject, written), 0},
128 {NULL} /* Sentinel */
129};
130
131static PyTypeObject _PyExc_BlockingIOError = {
132 PyVarObject_HEAD_INIT(NULL, 0)
133 "BlockingIOError", /*tp_name*/
134 sizeof(PyBlockingIOErrorObject), /*tp_basicsize*/
135 0, /*tp_itemsize*/
136 0, /*tp_dealloc*/
137 0, /*tp_print*/
138 0, /*tp_getattr*/
139 0, /*tp_setattr*/
140 0, /*tp_compare */
141 0, /*tp_repr*/
142 0, /*tp_as_number*/
143 0, /*tp_as_sequence*/
144 0, /*tp_as_mapping*/
145 0, /*tp_hash */
146 0, /*tp_call*/
147 0, /*tp_str*/
148 0, /*tp_getattro*/
149 0, /*tp_setattro*/
150 0, /*tp_as_buffer*/
151 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
152 PyDoc_STR("Exception raised when I/O would block "
153 "on a non-blocking I/O stream"), /* tp_doc */
154 0, /* tp_traverse */
155 0, /* tp_clear */
156 0, /* tp_richcompare */
157 0, /* tp_weaklistoffset */
158 0, /* tp_iter */
159 0, /* tp_iternext */
160 0, /* tp_methods */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000161 blockingioerror_members, /* tp_members */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000162 0, /* tp_getset */
163 0, /* tp_base */
164 0, /* tp_dict */
165 0, /* tp_descr_get */
166 0, /* tp_descr_set */
167 0, /* tp_dictoffset */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000168 (initproc)blockingioerror_init, /* tp_init */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000169 0, /* tp_alloc */
170 0, /* tp_new */
171};
172PyObject *PyExc_BlockingIOError = (PyObject *)&_PyExc_BlockingIOError;
173
174
175/*
176 * The main open() function
177 */
178PyDoc_STRVAR(open_doc,
179"Open file and return a stream. Raise IOError upon failure.\n"
180"\n"
181"file is either a text or byte string giving the name (and the path\n"
182"if the file isn't in the current working directory) of the file to\n"
183"be opened or an integer file descriptor of the file to be\n"
184"wrapped. (If a file descriptor is given, it is closed when the\n"
185"returned I/O object is closed, unless closefd is set to False.)\n"
186"\n"
187"mode is an optional string that specifies the mode in which the file\n"
188"is opened. It defaults to 'r' which means open for reading in text\n"
189"mode. Other common values are 'w' for writing (truncating the file if\n"
190"it already exists), and 'a' for appending (which on some Unix systems,\n"
191"means that all writes append to the end of the file regardless of the\n"
192"current seek position). In text mode, if encoding is not specified the\n"
193"encoding used is platform dependent. (For reading and writing raw\n"
194"bytes use binary mode and leave encoding unspecified.) The available\n"
195"modes are:\n"
196"\n"
197"========= ===============================================================\n"
198"Character Meaning\n"
199"--------- ---------------------------------------------------------------\n"
200"'r' open for reading (default)\n"
201"'w' open for writing, truncating the file first\n"
202"'a' open for writing, appending to the end of the file if it exists\n"
203"'b' binary mode\n"
204"'t' text mode (default)\n"
205"'+' open a disk file for updating (reading and writing)\n"
206"'U' universal newline mode (for backwards compatibility; unneeded\n"
207" for new code)\n"
208"========= ===============================================================\n"
209"\n"
210"The default mode is 'rt' (open for reading text). For binary random\n"
211"access, the mode 'w+b' opens and truncates the file to 0 bytes, while\n"
212"'r+b' opens the file without truncation.\n"
213"\n"
214"Python distinguishes between files opened in binary and text modes,\n"
215"even when the underlying operating system doesn't. Files opened in\n"
216"binary mode (appending 'b' to the mode argument) return contents as\n"
217"bytes objects without any decoding. In text mode (the default, or when\n"
218"'t' is appended to the mode argument), the contents of the file are\n"
219"returned as strings, the bytes having been first decoded using a\n"
220"platform-dependent encoding or using the specified encoding if given.\n"
221"\n"
222"buffering is an optional integer used to set the buffering policy. By\n"
223"default full buffering is on. Pass 0 to switch buffering off (only\n"
224"allowed in binary mode), 1 to set line buffering, and an integer > 1\n"
225"for full buffering.\n"
226"\n"
227"encoding is the name of the encoding used to decode or encode the\n"
228"file. This should only be used in text mode. The default encoding is\n"
229"platform dependent, but any encoding supported by Python can be\n"
230"passed. See the codecs module for the list of supported encodings.\n"
231"\n"
232"errors is an optional string that specifies how encoding errors are to\n"
233"be handled---this argument should not be used in binary mode. Pass\n"
234"'strict' to raise a ValueError exception if there is an encoding error\n"
235"(the default of None has the same effect), or pass 'ignore' to ignore\n"
236"errors. (Note that ignoring encoding errors can lead to data loss.)\n"
237"See the documentation for codecs.register for a list of the permitted\n"
238"encoding error strings.\n"
239"\n"
240"newline controls how universal newlines works (it only applies to text\n"
241"mode). It can be None, '', '\\n', '\\r', and '\\r\\n'. It works as\n"
242"follows:\n"
243"\n"
244"* On input, if newline is None, universal newlines mode is\n"
245" enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and\n"
246" these are translated into '\\n' before being returned to the\n"
247" caller. If it is '', universal newline mode is enabled, but line\n"
248" endings are returned to the caller untranslated. If it has any of\n"
249" the other legal values, input lines are only terminated by the given\n"
250" string, and the line ending is returned to the caller untranslated.\n"
251"\n"
252"* On output, if newline is None, any '\\n' characters written are\n"
253" translated to the system default line separator, os.linesep. If\n"
254" newline is '', no translation takes place. If newline is any of the\n"
255" other legal values, any '\\n' characters written are translated to\n"
256" the given string.\n"
257"\n"
258"If closefd is False, the underlying file descriptor will be kept open\n"
259"when the file is closed. This does not work when a file name is given\n"
260"and must be True in that case.\n"
261"\n"
262"open() returns a file object whose type depends on the mode, and\n"
263"through which the standard file operations such as reading and writing\n"
264"are performed. When open() is used to open a file in a text mode ('w',\n"
265"'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open\n"
266"a file in a binary mode, the returned class varies: in read binary\n"
267"mode, it returns a BufferedReader; in write binary and append binary\n"
268"modes, it returns a BufferedWriter, and in read/write mode, it returns\n"
269"a BufferedRandom.\n"
270"\n"
271"It is also possible to use a string or bytearray as a file for both\n"
272"reading and writing. For strings StringIO can be used like a file\n"
273"opened in a text mode, and for bytes a BytesIO can be used like a file\n"
274"opened in a binary mode.\n"
275 );
276
277static PyObject *
278io_open(PyObject *self, PyObject *args, PyObject *kwds)
279{
280 char *kwlist[] = {"file", "mode", "buffering",
281 "encoding", "errors", "newline",
282 "closefd", NULL};
283 PyObject *file;
284 char *mode = "r";
285 int buffering = -1, closefd = 1;
286 char *encoding = NULL, *errors = NULL, *newline = NULL;
287 unsigned i;
288
289 int reading = 0, writing = 0, appending = 0, updating = 0;
290 int text = 0, binary = 0, universal = 0;
291
292 char rawmode[5], *m;
293 int line_buffering, isatty;
294
295 PyObject *raw, *modeobj = NULL, *buffer = NULL, *wrapper = NULL;
296
297 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|sizzzi:open", kwlist,
298 &file, &mode, &buffering,
299 &encoding, &errors, &newline,
300 &closefd)) {
301 return NULL;
302 }
303
304 if (!PyUnicode_Check(file) &&
305 !PyBytes_Check(file) &&
306 !PyNumber_Check(file)) {
307 PyErr_Format(PyExc_TypeError, "invalid file: %R", file);
308 return NULL;
309 }
310
311 /* Decode mode */
312 for (i = 0; i < strlen(mode); i++) {
313 char c = mode[i];
314
315 switch (c) {
316 case 'r':
317 reading = 1;
318 break;
319 case 'w':
320 writing = 1;
321 break;
322 case 'a':
323 appending = 1;
324 break;
325 case '+':
326 updating = 1;
327 break;
328 case 't':
329 text = 1;
330 break;
331 case 'b':
332 binary = 1;
333 break;
334 case 'U':
335 universal = 1;
336 reading = 1;
337 break;
338 default:
339 goto invalid_mode;
340 }
341
342 /* c must not be duplicated */
343 if (strchr(mode+i+1, c)) {
344 invalid_mode:
345 PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode);
346 return NULL;
347 }
348
349 }
350
351 m = rawmode;
352 if (reading) *(m++) = 'r';
353 if (writing) *(m++) = 'w';
354 if (appending) *(m++) = 'a';
355 if (updating) *(m++) = '+';
356 *m = '\0';
357
358 /* Parameters validation */
359 if (universal) {
360 if (writing || appending) {
361 PyErr_SetString(PyExc_ValueError,
362 "can't use U and writing mode at once");
363 return NULL;
364 }
365 reading = 1;
366 }
367
368 if (text && binary) {
369 PyErr_SetString(PyExc_ValueError,
370 "can't have text and binary mode at once");
371 return NULL;
372 }
373
374 if (reading + writing + appending > 1) {
375 PyErr_SetString(PyExc_ValueError,
376 "must have exactly one of read/write/append mode");
377 return NULL;
378 }
379
380 if (binary && encoding != NULL) {
381 PyErr_SetString(PyExc_ValueError,
382 "binary mode doesn't take an encoding argument");
383 return NULL;
384 }
385
386 if (binary && errors != NULL) {
387 PyErr_SetString(PyExc_ValueError,
388 "binary mode doesn't take an errors argument");
389 return NULL;
390 }
391
392 if (binary && newline != NULL) {
393 PyErr_SetString(PyExc_ValueError,
394 "binary mode doesn't take a newline argument");
395 return NULL;
396 }
397
398 /* Create the Raw file stream */
399 raw = PyObject_CallFunction((PyObject *)&PyFileIO_Type,
400 "Osi", file, rawmode, closefd);
401 if (raw == NULL)
402 return NULL;
403
404 modeobj = PyUnicode_FromString(mode);
405 if (modeobj == NULL)
406 goto error;
407
408 /* buffering */
409 {
410 PyObject *res = PyObject_CallMethod(raw, "isatty", NULL);
411 if (res == NULL)
412 goto error;
413 isatty = PyLong_AsLong(res);
414 Py_DECREF(res);
415 if (isatty == -1 && PyErr_Occurred())
416 goto error;
417 }
418
419 if (buffering == 1 || (buffering < 0 && isatty)) {
420 buffering = -1;
421 line_buffering = 1;
422 }
423 else
424 line_buffering = 0;
425
426 if (buffering < 0) {
427 buffering = DEFAULT_BUFFER_SIZE;
428#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
429 {
430 struct stat st;
431 long fileno;
432 PyObject *res = PyObject_CallMethod(raw, "fileno", NULL);
433 if (res == NULL)
434 goto error;
435
436 fileno = PyLong_AsLong(res);
437 Py_DECREF(res);
438 if (fileno == -1 && PyErr_Occurred())
439 goto error;
440
441 if (fstat(fileno, &st) >= 0)
442 buffering = st.st_blksize;
443 }
444#endif
445 }
446 if (buffering < 0) {
447 PyErr_SetString(PyExc_ValueError,
448 "invalid buffering size");
449 goto error;
450 }
451
452 /* if not buffering, returns the raw file object */
453 if (buffering == 0) {
454 if (!binary) {
455 PyErr_SetString(PyExc_ValueError,
456 "can't have unbuffered text I/O");
457 goto error;
458 }
459
460 Py_DECREF(modeobj);
461 return raw;
462 }
463
464 /* wraps into a buffered file */
465 {
466 PyObject *Buffered_class;
467
468 if (updating)
469 Buffered_class = (PyObject *)&PyBufferedRandom_Type;
470 else if (writing || appending)
471 Buffered_class = (PyObject *)&PyBufferedWriter_Type;
472 else if (reading)
473 Buffered_class = (PyObject *)&PyBufferedReader_Type;
474 else {
475 PyErr_Format(PyExc_ValueError,
476 "unknown mode: '%s'", mode);
477 goto error;
478 }
479
480 buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering);
481 }
482 Py_CLEAR(raw);
483 if (buffer == NULL)
484 goto error;
485
486
487 /* if binary, returns the buffered file */
488 if (binary) {
489 Py_DECREF(modeobj);
490 return buffer;
491 }
492
493 /* wraps into a TextIOWrapper */
494 wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type,
495 "Osssi",
496 buffer,
497 encoding, errors, newline,
498 line_buffering);
499 Py_CLEAR(buffer);
500 if (wrapper == NULL)
501 goto error;
502
503 if (PyObject_SetAttrString(wrapper, "mode", modeobj) < 0)
504 goto error;
505 Py_DECREF(modeobj);
506 return wrapper;
507
508 error:
509 Py_XDECREF(raw);
510 Py_XDECREF(modeobj);
511 Py_XDECREF(buffer);
512 Py_XDECREF(wrapper);
513 return NULL;
514}
515
516/*
517 * Private helpers for the io module.
518 */
519
520Py_off_t
521PyNumber_AsOff_t(PyObject *item, PyObject *err)
522{
523 Py_off_t result;
524 PyObject *runerr;
525 PyObject *value = PyNumber_Index(item);
526 if (value == NULL)
527 return -1;
528
529 /* We're done if PyLong_AsSsize_t() returns without error. */
530 result = PyLong_AsOff_t(value);
531 if (result != -1 || !(runerr = PyErr_Occurred()))
532 goto finish;
533
534 /* Error handling code -- only manage OverflowError differently */
535 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
536 goto finish;
537
538 PyErr_Clear();
539 /* If no error-handling desired then the default clipping
540 is sufficient.
541 */
542 if (!err) {
543 assert(PyLong_Check(value));
544 /* Whether or not it is less than or equal to
545 zero is determined by the sign of ob_size
546 */
547 if (_PyLong_Sign(value) < 0)
548 result = PY_OFF_T_MIN;
549 else
550 result = PY_OFF_T_MAX;
551 }
552 else {
553 /* Otherwise replace the error with caller's error object. */
554 PyErr_Format(err,
555 "cannot fit '%.200s' into an offset-sized integer",
556 item->ob_type->tp_name);
557 }
558
559 finish:
560 Py_DECREF(value);
561 return result;
562}
563
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000564
565/* Basically the "n" format code with the ability to turn None into -1. */
566int
567_PyIO_ConvertSsize_t(PyObject *obj, void *result) {
568 Py_ssize_t limit;
569 if (obj == Py_None) {
570 limit = -1;
571 }
572 else if (PyNumber_Check(obj)) {
573 limit = PyNumber_AsSsize_t(obj, PyExc_OverflowError);
574 if (limit == -1 && PyErr_Occurred())
575 return 0;
576 }
577 else {
578 PyErr_Format(PyExc_TypeError,
579 "integer argument expected, got '%.200s'",
580 Py_TYPE(obj)->tp_name);
581 return 0;
582 }
583 *((Py_ssize_t *)result) = limit;
584 return 1;
585}
586
587
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000588static int
589iomodule_traverse(PyObject *mod, visitproc visit, void *arg) {
590 _PyIO_State *state = IO_MOD_STATE(mod);
591 if (!state->initialized)
592 return 0;
593 Py_VISIT(state->os_module);
594 if (state->locale_module != NULL) {
595 Py_VISIT(state->locale_module);
596 }
597 Py_VISIT(state->unsupported_operation);
598 return 0;
599}
600
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000601
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000602static int
603iomodule_clear(PyObject *mod) {
604 _PyIO_State *state = IO_MOD_STATE(mod);
605 if (!state->initialized)
606 return 0;
607 Py_CLEAR(state->os_module);
608 if (state->locale_module != NULL)
609 Py_CLEAR(state->locale_module);
610 Py_CLEAR(state->unsupported_operation);
611 return 0;
612}
613
614static void
615iomodule_free(PyObject *mod) {
616 iomodule_clear(mod);
617}
618
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000619
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000620/*
621 * Module definition
622 */
623
624static PyMethodDef module_methods[] = {
625 {"open", (PyCFunction)io_open, METH_VARARGS|METH_KEYWORDS, open_doc},
626 {NULL, NULL}
627};
628
629struct PyModuleDef _PyIO_Module = {
630 PyModuleDef_HEAD_INIT,
631 "io",
632 module_doc,
633 sizeof(_PyIO_State),
634 module_methods,
635 NULL,
636 iomodule_traverse,
637 iomodule_clear,
638 (freefunc)iomodule_free,
639};
640
641PyMODINIT_FUNC
642PyInit__io(void)
643{
644 PyObject *m = PyModule_Create(&_PyIO_Module);
645 _PyIO_State *state = NULL;
646 if (m == NULL)
647 return NULL;
648 state = IO_MOD_STATE(m);
649 state->initialized = 0;
650
651 /* put os in the module state */
652 state->os_module = PyImport_ImportModule("os");
653 if (state->os_module == NULL)
654 goto fail;
655
656#define ADD_TYPE(type, name) \
657 if (PyType_Ready(type) < 0) \
658 goto fail; \
659 Py_INCREF(type); \
660 if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
661 Py_DECREF(type); \
662 goto fail; \
663 }
664
665 /* DEFAULT_BUFFER_SIZE */
666 if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
667 goto fail;
668
669 /* UnsupportedOperation inherits from ValueError and IOError */
670 state->unsupported_operation = PyObject_CallFunction(
671 (PyObject *)&PyType_Type, "s(OO){}",
672 "UnsupportedOperation", PyExc_ValueError, PyExc_IOError);
673 if (state->unsupported_operation == NULL)
674 goto fail;
675 Py_INCREF(state->unsupported_operation);
676 if (PyModule_AddObject(m, "UnsupportedOperation",
677 state->unsupported_operation) < 0)
678 goto fail;
679
680 /* BlockingIOError */
681 _PyExc_BlockingIOError.tp_base = (PyTypeObject *) PyExc_IOError;
682 ADD_TYPE(&_PyExc_BlockingIOError, "BlockingIOError");
683
684 /* Concrete base types of the IO ABCs.
685 (the ABCs themselves are declared through inheritance in io.py)
686 */
687 ADD_TYPE(&PyIOBase_Type, "_IOBase");
688 ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
689 ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
690 ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");
691
692 /* Implementation of concrete IO objects. */
693 /* FileIO */
694 PyFileIO_Type.tp_base = &PyRawIOBase_Type;
695 ADD_TYPE(&PyFileIO_Type, "FileIO");
696
697 /* BytesIO */
698 PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
699 ADD_TYPE(&PyBytesIO_Type, "BytesIO");
700
701 /* StringIO */
702 PyStringIO_Type.tp_base = &PyTextIOBase_Type;
703 ADD_TYPE(&PyStringIO_Type, "StringIO");
704
705 /* BufferedReader */
706 PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
707 ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");
708
709 /* BufferedWriter */
710 PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
711 ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");
712
713 /* BufferedRWPair */
714 PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
715 ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");
716
717 /* BufferedRandom */
718 PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
719 ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");
720
721 /* TextIOWrapper */
722 PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
723 ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");
724
725 /* IncrementalNewlineDecoder */
726 ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");
727
728 /* Interned strings */
729 if (!(_PyIO_str_close = PyUnicode_InternFromString("close")))
730 goto fail;
731 if (!(_PyIO_str_closed = PyUnicode_InternFromString("closed")))
732 goto fail;
733 if (!(_PyIO_str_decode = PyUnicode_InternFromString("decode")))
734 goto fail;
735 if (!(_PyIO_str_encode = PyUnicode_InternFromString("encode")))
736 goto fail;
737 if (!(_PyIO_str_fileno = PyUnicode_InternFromString("fileno")))
738 goto fail;
739 if (!(_PyIO_str_flush = PyUnicode_InternFromString("flush")))
740 goto fail;
741 if (!(_PyIO_str_getstate = PyUnicode_InternFromString("getstate")))
742 goto fail;
743 if (!(_PyIO_str_isatty = PyUnicode_InternFromString("isatty")))
744 goto fail;
745 if (!(_PyIO_str_newlines = PyUnicode_InternFromString("newlines")))
746 goto fail;
747 if (!(_PyIO_str_nl = PyUnicode_InternFromString("\n")))
748 goto fail;
749 if (!(_PyIO_str_read = PyUnicode_InternFromString("read")))
750 goto fail;
751 if (!(_PyIO_str_read1 = PyUnicode_InternFromString("read1")))
752 goto fail;
753 if (!(_PyIO_str_readable = PyUnicode_InternFromString("readable")))
754 goto fail;
755 if (!(_PyIO_str_readinto = PyUnicode_InternFromString("readinto")))
756 goto fail;
757 if (!(_PyIO_str_readline = PyUnicode_InternFromString("readline")))
758 goto fail;
759 if (!(_PyIO_str_reset = PyUnicode_InternFromString("reset")))
760 goto fail;
761 if (!(_PyIO_str_seek = PyUnicode_InternFromString("seek")))
762 goto fail;
763 if (!(_PyIO_str_seekable = PyUnicode_InternFromString("seekable")))
764 goto fail;
Antoine Pitroue4501852009-05-14 18:55:55 +0000765 if (!(_PyIO_str_setstate = PyUnicode_InternFromString("setstate")))
766 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000767 if (!(_PyIO_str_tell = PyUnicode_InternFromString("tell")))
768 goto fail;
769 if (!(_PyIO_str_truncate = PyUnicode_InternFromString("truncate")))
770 goto fail;
771 if (!(_PyIO_str_write = PyUnicode_InternFromString("write")))
772 goto fail;
773 if (!(_PyIO_str_writable = PyUnicode_InternFromString("writable")))
774 goto fail;
775
776 if (!(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
777 goto fail;
778 if (!(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
779 goto fail;
Antoine Pitroue4501852009-05-14 18:55:55 +0000780 if (!(_PyIO_zero = PyLong_FromLong(0L)))
781 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000782
783 state->initialized = 1;
784
785 return m;
786
787 fail:
788 Py_XDECREF(state->os_module);
789 Py_XDECREF(state->unsupported_operation);
790 Py_DECREF(m);
791 return NULL;
792}