Coverage Report

Created: 2026-11-30 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Modules/_io/clinic/_iomodule.c.h
Line
Count
Source
1
/*[clinic input]
2
preserve
3
[clinic start generated code]*/
4
5
#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
6
#  include "pycore_gc.h"          // PyGC_Head
7
#  include "pycore_runtime.h"     // _Py_ID()
8
#endif
9
#include "pycore_modsupport.h"    // _PyArg_UnpackKeywords()
10
#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
11
12
PyDoc_STRVAR(_io_open__doc__,
13
"open($module, /, file, mode=\'r\', buffering=-1, encoding=None,\n"
14
"     errors=None, newline=None, closefd=True, opener=None)\n"
15
"--\n"
16
"\n"
17
"Open file and return a stream.  Raise OSError upon failure.\n"
18
"\n"
19
"file is either a text or byte string giving the name (and the path\n"
20
"if the file isn\'t in the current working directory) of the file to\n"
21
"be opened or an integer file descriptor of the file to be\n"
22
"wrapped.  (If a file descriptor is given, it is closed when the\n"
23
"returned I/O object is closed, unless closefd is set to False.)\n"
24
"\n"
25
"mode is an optional string that specifies the mode in which the file\n"
26
"is opened.  It defaults to \'r\' which means open for reading in text\n"
27
"mode.  Other common values are \'w\' for writing (truncating the file if\n"
28
"it already exists), \'x\' for creating and writing to a new file, and\n"
29
"\'a\' for appending (which on some Unix systems, means that all writes\n"
30
"append to the end of the file regardless of the current seek position).\n"
31
"The available modes are:\n"
32
"\n"
33
"========= ==========================================================\n"
34
"Character Meaning\n"
35
"--------- ----------------------------------------------------------\n"
36
"\'r\'       open for reading (default)\n"
37
"\'w\'       open for writing, truncating the file first\n"
38
"\'x\'       create a new file and open it for writing\n"
39
"\'a\'       open for writing, appending to the end of the file if it\n"
40
"          exists\n"
41
"\'b\'       binary mode\n"
42
"\'t\'       text mode (default)\n"
43
"\'+\'       open a disk file for updating (reading and writing)\n"
44
"========= ==========================================================\n"
45
"\n"
46
"The default mode is \'rt\' (open for reading text).  For binary random\n"
47
"access, the mode \'w+b\' opens and truncates the file to 0 bytes, while\n"
48
"\'r+b\' opens the file without truncation.  The \'x\' mode implies \'w\' and\n"
49
"raises an `FileExistsError` if the file already exists.\n"
50
"\n"
51
"Python distinguishes between files opened in binary and text modes,\n"
52
"even when the underlying operating system doesn\'t.  Files opened in\n"
53
"binary mode (appending \'b\' to the mode argument) return contents as\n"
54
"bytes objects without any decoding.  In text mode (the default, or when\n"
55
"\'t\' is appended to the mode argument), the contents of the file are\n"
56
"decoded using the encoding described below and returned as strings.\n"
57
"\n"
58
"buffering is an optional integer used to set the buffering policy.\n"
59
"Pass 0 to switch buffering off (only allowed in binary mode), 1 to\n"
60
"select line buffering (only usable in text mode), and an integer > 1 to\n"
61
"indicate the size of a fixed-size chunk buffer.   When no buffering\n"
62
"argument is given, the default buffering policy works as follows:\n"
63
"\n"
64
"* Binary files are buffered in fixed-size chunks; the size of the buffer\n"
65
"  is max(min(blocksize, 8 MiB), DEFAULT_BUFFER_SIZE) when the device\n"
66
"  block size is available.\n"
67
"  On most systems, the buffer will typically be 128 kilobytes long.\n"
68
"\n"
69
"* \"Interactive\" text files (files for which isatty() returns True)\n"
70
"  use line buffering.  Other text files use the policy described above\n"
71
"  for binary files.\n"
72
"\n"
73
"encoding is the name of the encoding used to decode or encode the file.\n"
74
"This should only be used in text mode.  The default encoding is UTF-8;\n"
75
"if UTF-8 Mode is disabled, the encoding returned by\n"
76
"locale.getencoding() is used instead.  See the codecs module for the\n"
77
"list of supported encodings.\n"
78
"\n"
79
"errors is an optional string that specifies how encoding errors are to\n"
80
"be handled---this argument should not be used in binary mode.  Pass\n"
81
"\'strict\' to raise a ValueError exception if there is an encoding error\n"
82
"(the default of None has the same effect), or pass \'ignore\' to ignore\n"
83
"errors.  (Note that ignoring encoding errors can lead to data loss.)\n"
84
"See the documentation for codecs.register or run \'help(codecs.Codec)\'\n"
85
"for a list of the permitted encoding error strings.\n"
86
"\n"
87
"newline controls how universal newlines works (it only applies to text\n"
88
"mode).  It can be None, \'\', \'\\n\', \'\\r\', and \'\\r\\n\'.  It works as\n"
89
"follows:\n"
90
"\n"
91
"* On input, if newline is None, universal newlines mode is enabled.\n"
92
"  Lines in the input can end in \'\\n\', \'\\r\', or \'\\r\\n\', and these are\n"
93
"  translated into \'\\n\' before being returned to the caller.  If it is\n"
94
"  \'\', universal newline mode is enabled, but line endings are returned\n"
95
"  to the caller untranslated.  If it has any of the other legal values,\n"
96
"  input lines are only terminated by the given string, and the line\n"
97
"  ending is returned to the caller untranslated.\n"
98
"\n"
99
"* On output, if newline is None, any \'\\n\' characters written are\n"
100
"  translated to the system default line separator, os.linesep.  If\n"
101
"  newline is \'\' or \'\\n\', no translation takes place.  If newline is any\n"
102
"  of the other legal values, any \'\\n\' characters written are translated\n"
103
"  to the given string.\n"
104
"\n"
105
"If closefd is False, the underlying file descriptor will be kept open\n"
106
"when the file is closed.  This does not work when a file name is given\n"
107
"and must be True in that case.\n"
108
"\n"
109
"A custom opener can be used by passing a callable as *opener*.  The\n"
110
"underlying file descriptor for the file object is then obtained by\n"
111
"calling *opener* with (*file*, *flags*).  *opener* must return an open\n"
112
"file descriptor (passing os.open as *opener* results in functionality\n"
113
"similar to passing None).\n"
114
"\n"
115
"open() returns a file object whose type depends on the mode, and\n"
116
"through which the standard file operations such as reading and writing\n"
117
"are performed.  When open() is used to open a file in a text mode (\'w\',\n"
118
"\'r\', \'wt\', \'rt\', etc.), it returns a TextIOWrapper.  When used to open\n"
119
"a file in a binary mode, the returned class varies: in read binary\n"
120
"mode, it returns a BufferedReader; in write binary and append binary\n"
121
"modes, it returns a BufferedWriter, and in read/write mode, it returns\n"
122
"a BufferedRandom.\n"
123
"\n"
124
"It is also possible to use a string or bytearray as a file for both\n"
125
"reading and writing.  For strings StringIO can be used like a file\n"
126
"opened in a text mode, and for bytes a BytesIO can be used like a file\n"
127
"opened in a binary mode.");
128
129
#define _IO_OPEN_METHODDEF    \
130
    {"open", _PyCFunction_CAST(_io_open), METH_FASTCALL|METH_KEYWORDS, _io_open__doc__},
131
132
static PyObject *
133
_io_open_impl(PyObject *module, PyObject *file, const char *mode,
134
              int buffering, const char *encoding, const char *errors,
135
              const char *newline, int closefd, PyObject *opener);
136
137
static PyObject *
138
_io_open(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
139
461
{
140
461
    PyObject *return_value = NULL;
141
461
    #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
142
143
461
    #define NUM_KEYWORDS 8
144
461
    static struct {
145
461
        PyGC_Head _this_is_not_used;
146
461
        PyObject_VAR_HEAD
147
461
        Py_hash_t ob_hash;
148
461
        PyObject *ob_item[NUM_KEYWORDS];
149
461
    } _kwtuple = {
150
461
        .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
151
461
        .ob_hash = -1,
152
461
        .ob_item = { &_Py_ID(file), &_Py_ID(mode), &_Py_ID(buffering), &_Py_ID(encoding), &_Py_ID(errors), &_Py_ID(newline), &_Py_ID(closefd), &_Py_ID(opener), },
153
461
    };
154
461
    #undef NUM_KEYWORDS
155
461
    #define KWTUPLE (&_kwtuple.ob_base.ob_base)
156
157
    #else  // !Py_BUILD_CORE
158
    #  define KWTUPLE NULL
159
    #endif  // !Py_BUILD_CORE
160
161
461
    static const char * const _keywords[] = {"file", "mode", "buffering", "encoding", "errors", "newline", "closefd", "opener", NULL};
162
461
    static _PyArg_Parser _parser = {
163
461
        .keywords = _keywords,
164
461
        .fname = "open",
165
461
        .kwtuple = KWTUPLE,
166
461
    };
167
461
    #undef KWTUPLE
168
461
    PyObject *argsbuf[8];
169
461
    Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 1;
170
461
    PyObject *file;
171
461
    const char *mode = "r";
172
461
    int buffering = -1;
173
461
    const char *encoding = NULL;
174
461
    const char *errors = NULL;
175
461
    const char *newline = NULL;
176
461
    int closefd = 1;
177
461
    PyObject *opener = Py_None;
178
179
461
    args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
180
461
            /*minpos*/ 1, /*maxpos*/ 8, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
181
461
    if (!args) {
182
0
        goto exit;
183
0
    }
184
461
    file = args[0];
185
461
    if (!noptargs) {
186
0
        goto skip_optional_pos;
187
0
    }
188
461
    if (args[1]) {
189
461
        if (!PyUnicode_Check(args[1])) {
190
0
            _PyArg_BadArgument("open", "argument 'mode'", "str", args[1]);
191
0
            goto exit;
192
0
        }
193
461
        mode = _PyUnicode_AsUTF8NoNUL(args[1]);
194
461
        if (mode == NULL) {
195
0
            goto exit;
196
0
        }
197
461
        if (!--noptargs) {
198
395
            goto skip_optional_pos;
199
395
        }
200
461
    }
201
66
    if (args[2]) {
202
66
        buffering = PyLong_AsInt(args[2]);
203
66
        if (buffering == -1 && PyErr_Occurred()) {
204
0
            goto exit;
205
0
        }
206
66
        if (!--noptargs) {
207
0
            goto skip_optional_pos;
208
0
        }
209
66
    }
210
66
    if (args[3]) {
211
66
        if (args[3] == Py_None) {
212
66
            encoding = NULL;
213
66
        }
214
0
        else if (PyUnicode_Check(args[3])) {
215
0
            encoding = _PyUnicode_AsUTF8NoNUL(args[3]);
216
0
            if (encoding == NULL) {
217
0
                goto exit;
218
0
            }
219
0
        }
220
0
        else {
221
0
            _PyArg_BadArgument("open", "argument 'encoding'", "str or None", args[3]);
222
0
            goto exit;
223
0
        }
224
66
        if (!--noptargs) {
225
0
            goto skip_optional_pos;
226
0
        }
227
66
    }
228
66
    if (args[4]) {
229
66
        if (args[4] == Py_None) {
230
66
            errors = NULL;
231
66
        }
232
0
        else if (PyUnicode_Check(args[4])) {
233
0
            errors = _PyUnicode_AsUTF8NoNUL(args[4]);
234
0
            if (errors == NULL) {
235
0
                goto exit;
236
0
            }
237
0
        }
238
0
        else {
239
0
            _PyArg_BadArgument("open", "argument 'errors'", "str or None", args[4]);
240
0
            goto exit;
241
0
        }
242
66
        if (!--noptargs) {
243
0
            goto skip_optional_pos;
244
0
        }
245
66
    }
246
66
    if (args[5]) {
247
66
        if (args[5] == Py_None) {
248
66
            newline = NULL;
249
66
        }
250
0
        else if (PyUnicode_Check(args[5])) {
251
0
            newline = _PyUnicode_AsUTF8NoNUL(args[5]);
252
0
            if (newline == NULL) {
253
0
                goto exit;
254
0
            }
255
0
        }
256
0
        else {
257
0
            _PyArg_BadArgument("open", "argument 'newline'", "str or None", args[5]);
258
0
            goto exit;
259
0
        }
260
66
        if (!--noptargs) {
261
0
            goto skip_optional_pos;
262
0
        }
263
66
    }
264
66
    if (args[6]) {
265
66
        closefd = PyObject_IsTrue(args[6]);
266
66
        if (closefd < 0) {
267
0
            goto exit;
268
0
        }
269
66
        if (!--noptargs) {
270
66
            goto skip_optional_pos;
271
66
        }
272
66
    }
273
0
    opener = args[7];
274
461
skip_optional_pos:
275
461
    return_value = _io_open_impl(module, file, mode, buffering, encoding, errors, newline, closefd, opener);
276
277
461
exit:
278
461
    return return_value;
279
461
}
280
281
PyDoc_STRVAR(_io_text_encoding__doc__,
282
"text_encoding($module, encoding, stacklevel=2, /)\n"
283
"--\n"
284
"\n"
285
"A helper function to choose the text encoding.\n"
286
"\n"
287
"When encoding is not None, this function returns it.\n"
288
"Otherwise, this function returns the default text encoding\n"
289
"(i.e. \"locale\" or \"utf-8\" depends on UTF-8 mode).\n"
290
"\n"
291
"This function emits an EncodingWarning if encoding is None and\n"
292
"sys.flags.warn_default_encoding is true.\n"
293
"\n"
294
"This can be used in APIs with an encoding=None parameter.\n"
295
"However, please consider using encoding=\"utf-8\" for new APIs.");
296
297
#define _IO_TEXT_ENCODING_METHODDEF    \
298
    {"text_encoding", _PyCFunction_CAST(_io_text_encoding), METH_FASTCALL, _io_text_encoding__doc__},
299
300
static PyObject *
301
_io_text_encoding_impl(PyObject *module, PyObject *encoding, int stacklevel);
302
303
static PyObject *
304
_io_text_encoding(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
305
0
{
306
0
    PyObject *return_value = NULL;
307
0
    PyObject *encoding;
308
0
    int stacklevel = 2;
309
310
0
    if (!_PyArg_CheckPositional("text_encoding", nargs, 1, 2)) {
311
0
        goto exit;
312
0
    }
313
0
    encoding = args[0];
314
0
    if (nargs < 2) {
315
0
        goto skip_optional;
316
0
    }
317
0
    stacklevel = PyLong_AsInt(args[1]);
318
0
    if (stacklevel == -1 && PyErr_Occurred()) {
319
0
        goto exit;
320
0
    }
321
0
skip_optional:
322
0
    return_value = _io_text_encoding_impl(module, encoding, stacklevel);
323
324
0
exit:
325
0
    return return_value;
326
0
}
327
328
PyDoc_STRVAR(_io_open_code__doc__,
329
"open_code($module, /, path)\n"
330
"--\n"
331
"\n"
332
"Opens the provided file with the intent to import the contents.\n"
333
"\n"
334
"This may perform extra validation beyond open(), but is otherwise\n"
335
"interchangeable with calling open(path, \'rb\').");
336
337
#define _IO_OPEN_CODE_METHODDEF    \
338
    {"open_code", _PyCFunction_CAST(_io_open_code), METH_FASTCALL|METH_KEYWORDS, _io_open_code__doc__},
339
340
static PyObject *
341
_io_open_code_impl(PyObject *module, PyObject *path);
342
343
static PyObject *
344
_io_open_code(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
345
395
{
346
395
    PyObject *return_value = NULL;
347
395
    #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
348
349
395
    #define NUM_KEYWORDS 1
350
395
    static struct {
351
395
        PyGC_Head _this_is_not_used;
352
395
        PyObject_VAR_HEAD
353
395
        Py_hash_t ob_hash;
354
395
        PyObject *ob_item[NUM_KEYWORDS];
355
395
    } _kwtuple = {
356
395
        .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
357
395
        .ob_hash = -1,
358
395
        .ob_item = { &_Py_ID(path), },
359
395
    };
360
395
    #undef NUM_KEYWORDS
361
395
    #define KWTUPLE (&_kwtuple.ob_base.ob_base)
362
363
    #else  // !Py_BUILD_CORE
364
    #  define KWTUPLE NULL
365
    #endif  // !Py_BUILD_CORE
366
367
395
    static const char * const _keywords[] = {"path", NULL};
368
395
    static _PyArg_Parser _parser = {
369
395
        .keywords = _keywords,
370
395
        .fname = "open_code",
371
395
        .kwtuple = KWTUPLE,
372
395
    };
373
395
    #undef KWTUPLE
374
395
    PyObject *argsbuf[1];
375
395
    PyObject *path;
376
377
395
    args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
378
395
            /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
379
395
    if (!args) {
380
0
        goto exit;
381
0
    }
382
395
    if (!PyUnicode_Check(args[0])) {
383
0
        _PyArg_BadArgument("open_code", "argument 'path'", "str", args[0]);
384
0
        goto exit;
385
0
    }
386
395
    path = args[0];
387
395
    return_value = _io_open_code_impl(module, path);
388
389
395
exit:
390
395
    return return_value;
391
395
}
392
/*[clinic end generated code: output=517d977e17d38fce input=a9049054013a1b77]*/