Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/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
22.3k
{
140
22.3k
    PyObject *return_value = NULL;
141
22.3k
    #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
142
143
22.3k
    #define NUM_KEYWORDS 8
144
22.3k
    static struct {
145
22.3k
        PyGC_Head _this_is_not_used;
146
22.3k
        PyObject_VAR_HEAD
147
22.3k
        Py_hash_t ob_hash;
148
22.3k
        PyObject *ob_item[NUM_KEYWORDS];
149
22.3k
    } _kwtuple = {
150
22.3k
        .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
151
22.3k
        .ob_hash = -1,
152
22.3k
        .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
22.3k
    };
154
22.3k
    #undef NUM_KEYWORDS
155
22.3k
    #define KWTUPLE (&_kwtuple.ob_base.ob_base)
156
157
    #else  // !Py_BUILD_CORE
158
    #  define KWTUPLE NULL
159
    #endif  // !Py_BUILD_CORE
160
161
22.3k
    static const char * const _keywords[] = {"file", "mode", "buffering", "encoding", "errors", "newline", "closefd", "opener", NULL};
162
22.3k
    static _PyArg_Parser _parser = {
163
22.3k
        .keywords = _keywords,
164
22.3k
        .fname = "open",
165
22.3k
        .kwtuple = KWTUPLE,
166
22.3k
    };
167
22.3k
    #undef KWTUPLE
168
22.3k
    PyObject *argsbuf[8];
169
22.3k
    Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 1;
170
22.3k
    PyObject *file;
171
22.3k
    const char *mode = "r";
172
22.3k
    int buffering = -1;
173
22.3k
    const char *encoding = NULL;
174
22.3k
    const char *errors = NULL;
175
22.3k
    const char *newline = NULL;
176
22.3k
    int closefd = 1;
177
22.3k
    PyObject *opener = Py_None;
178
179
22.3k
    args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
180
22.3k
            /*minpos*/ 1, /*maxpos*/ 8, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
181
22.3k
    if (!args) {
182
0
        goto exit;
183
0
    }
184
22.3k
    file = args[0];
185
22.3k
    if (!noptargs) {
186
0
        goto skip_optional_pos;
187
0
    }
188
22.3k
    if (args[1]) {
189
22.3k
        if (!PyUnicode_Check(args[1])) {
190
0
            _PyArg_BadArgument("open", "argument 'mode'", "str", args[1]);
191
0
            goto exit;
192
0
        }
193
22.3k
        mode = _PyUnicode_AsUTF8NoNUL(args[1]);
194
22.3k
        if (mode == NULL) {
195
0
            goto exit;
196
0
        }
197
22.3k
        if (!--noptargs) {
198
22.1k
            goto skip_optional_pos;
199
22.1k
        }
200
22.3k
    }
201
124
    if (args[2]) {
202
124
        buffering = PyLong_AsInt(args[2]);
203
124
        if (buffering == -1 && PyErr_Occurred()) {
204
0
            goto exit;
205
0
        }
206
124
        if (!--noptargs) {
207
0
            goto skip_optional_pos;
208
0
        }
209
124
    }
210
124
    if (args[3]) {
211
124
        if (args[3] == Py_None) {
212
111
            encoding = NULL;
213
111
        }
214
13
        else if (PyUnicode_Check(args[3])) {
215
13
            encoding = _PyUnicode_AsUTF8NoNUL(args[3]);
216
13
            if (encoding == NULL) {
217
0
                goto exit;
218
0
            }
219
13
        }
220
0
        else {
221
0
            _PyArg_BadArgument("open", "argument 'encoding'", "str or None", args[3]);
222
0
            goto exit;
223
0
        }
224
124
        if (!--noptargs) {
225
0
            goto skip_optional_pos;
226
0
        }
227
124
    }
228
124
    if (args[4]) {
229
124
        if (args[4] == Py_None) {
230
124
            errors = NULL;
231
124
        }
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
124
        if (!--noptargs) {
243
0
            goto skip_optional_pos;
244
0
        }
245
124
    }
246
124
    if (args[5]) {
247
124
        if (args[5] == Py_None) {
248
124
            newline = NULL;
249
124
        }
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
124
        if (!--noptargs) {
261
13
            goto skip_optional_pos;
262
13
        }
263
124
    }
264
111
    if (args[6]) {
265
111
        closefd = PyObject_IsTrue(args[6]);
266
111
        if (closefd < 0) {
267
0
            goto exit;
268
0
        }
269
111
        if (!--noptargs) {
270
111
            goto skip_optional_pos;
271
111
        }
272
111
    }
273
0
    opener = args[7];
274
22.3k
skip_optional_pos:
275
22.3k
    return_value = _io_open_impl(module, file, mode, buffering, encoding, errors, newline, closefd, opener);
276
277
22.3k
exit:
278
22.3k
    return return_value;
279
22.3k
}
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
26
{
306
26
    PyObject *return_value = NULL;
307
26
    PyObject *encoding;
308
26
    int stacklevel = 2;
309
310
26
    if (!_PyArg_CheckPositional("text_encoding", nargs, 1, 2)) {
311
0
        goto exit;
312
0
    }
313
26
    encoding = args[0];
314
26
    if (nargs < 2) {
315
26
        goto skip_optional;
316
26
    }
317
0
    stacklevel = PyLong_AsInt(args[1]);
318
0
    if (stacklevel == -1 && PyErr_Occurred()) {
319
0
        goto exit;
320
0
    }
321
26
skip_optional:
322
26
    return_value = _io_text_encoding_impl(module, encoding, stacklevel);
323
324
26
exit:
325
26
    return return_value;
326
26
}
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
2.07k
{
346
2.07k
    PyObject *return_value = NULL;
347
2.07k
    #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
348
349
2.07k
    #define NUM_KEYWORDS 1
350
2.07k
    static struct {
351
2.07k
        PyGC_Head _this_is_not_used;
352
2.07k
        PyObject_VAR_HEAD
353
2.07k
        Py_hash_t ob_hash;
354
2.07k
        PyObject *ob_item[NUM_KEYWORDS];
355
2.07k
    } _kwtuple = {
356
2.07k
        .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
357
2.07k
        .ob_hash = -1,
358
2.07k
        .ob_item = { &_Py_ID(path), },
359
2.07k
    };
360
2.07k
    #undef NUM_KEYWORDS
361
2.07k
    #define KWTUPLE (&_kwtuple.ob_base.ob_base)
362
363
    #else  // !Py_BUILD_CORE
364
    #  define KWTUPLE NULL
365
    #endif  // !Py_BUILD_CORE
366
367
2.07k
    static const char * const _keywords[] = {"path", NULL};
368
2.07k
    static _PyArg_Parser _parser = {
369
2.07k
        .keywords = _keywords,
370
2.07k
        .fname = "open_code",
371
2.07k
        .kwtuple = KWTUPLE,
372
2.07k
    };
373
2.07k
    #undef KWTUPLE
374
2.07k
    PyObject *argsbuf[1];
375
2.07k
    PyObject *path;
376
377
2.07k
    args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
378
2.07k
            /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
379
2.07k
    if (!args) {
380
0
        goto exit;
381
0
    }
382
2.07k
    if (!PyUnicode_Check(args[0])) {
383
0
        _PyArg_BadArgument("open_code", "argument 'path'", "str", args[0]);
384
0
        goto exit;
385
0
    }
386
2.07k
    path = args[0];
387
2.07k
    return_value = _io_open_code_impl(module, path);
388
389
2.07k
exit:
390
2.07k
    return return_value;
391
2.07k
}
392
/*[clinic end generated code: output=517d977e17d38fce input=a9049054013a1b77]*/