Skip to content

Commit 50f77b8

Browse files
Merge python#9
9: Warn for using built-in open r=ltratt a=nanjekyejoannah Warn for file open. I was struggling to support the generic case assuming io.open doesnt exist. A warning is simpler to do assuming support for >=2.6. I added notes in the Google doc for this. Co-authored-by: Joannah Nanjekye <jnanjekye@python.org>
2 parents 8241115 + af85bc9 commit 50f77b8

File tree

4 files changed

+24
-0
lines changed

4 files changed

+24
-0
lines changed

Doc/c-api/exceptions.rst

+5
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,11 @@ is a separate error indicator for each thread.
333333
334334
.. versionadded:: 2.6
335335
336+
.. c:function:: int PyErr_WarnPy3k_WithFix(char *message, char *fix, int stacklevel)
337+
338+
Issue a :exc:`DeprecationWarning` with the given *message* and *stacklevel*
339+
if the :c:data:`Py_Py3kWarningFlag` flag is enabled.
340+
336341
337342
.. c:function:: int PyErr_CheckSignals()
338343

Lib/test/test_py3kwarn.py

+14
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,20 @@ def test_file_xreadlines(self):
247247
with check_py3k_warnings() as w:
248248
self.assertWarning(f.xreadlines(), w, expected)
249249

250+
def test_file_open(self):
251+
expected = ("The builtin 'file()'/'open()' function is not supported in 3.x, "
252+
"use the 'io.open()' function instead with the encoding keyword argument")
253+
with open(__file__) as f:
254+
with check_py3k_warnings() as w:
255+
self.assertWarning(f.read(), w, expected)
256+
257+
def test_file(self):
258+
expected = ("The builtin 'file()'/'open()' function is not supported in 3.x, "
259+
"use the 'io.open()' function instead with the encoding keyword argument")
260+
with file(__file__) as f:
261+
with check_py3k_warnings() as w:
262+
self.assertWarning(f.read(), w, expected)
263+
250264
def test_hash_inheritance(self):
251265
with check_py3k_warnings() as w:
252266
# With object as the base class

Objects/fileobject.c

+4
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,10 @@ _PyFile_SanitizeMode(char *mode)
323323
static PyObject *
324324
open_the_file(PyFileObject *f, char *name, char *mode)
325325
{
326+
if (PyErr_WarnPy3k_WithFix("The builtin 'file()'/'open()' function is not supported in 3.x, ",
327+
"use the 'io.open()' function instead with the encoding keyword argument", 1) < 0)
328+
return NULL;
329+
326330
char *newmode;
327331
assert(f != NULL);
328332
assert(PyFile_Check(f));

Python/bltinmodule.c

+1
Original file line numberDiff line numberDiff line change
@@ -1507,6 +1507,7 @@ builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
15071507
return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
15081508
}
15091509

1510+
15101511
PyDoc_STRVAR(open_doc,
15111512
"open(name[, mode[, buffering]]) -> file object\n\
15121513
\n\

0 commit comments

Comments
 (0)