Skip to content

gh-74185: repr() of ImportError now contains attributes name and path. #1011

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
2 changes: 1 addition & 1 deletion Lib/test/test_baseexception.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def test_interface_single_arg(self):
exc = Exception(arg)
results = ([len(exc.args), 1], [exc.args[0], arg],
[str(exc), str(arg)],
[repr(exc), exc.__class__.__name__ + repr(exc.args)])
[repr(exc), '%s(%r)' % (exc.__class__.__name__, arg)])
self.interface_test_driver(results)

def test_interface_multi_arg(self):
Expand Down
30 changes: 30 additions & 0 deletions Lib/test/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1127,6 +1127,36 @@ def test_non_str_argument(self):
exc = ImportError(arg)
self.assertEqual(str(arg), str(exc))

def test_repr(self):
exc = ImportError()
self.assertEqual(repr(exc), "ImportError()")

exc = ImportError('test')
self.assertEqual(repr(exc), "ImportError('test')")

exc = ImportError('test', 'case')
self.assertEqual(repr(exc), "ImportError('test', 'case')")

exc = ImportError(name='somemodule')
self.assertEqual(repr(exc), "ImportError(name='somemodule')")

exc = ImportError('test', name='somemodule')
self.assertEqual(repr(exc), "ImportError('test', name='somemodule')")

exc = ImportError(path='somepath')
self.assertEqual(repr(exc), "ImportError(path='somepath')")

exc = ImportError('test', path='somepath')
self.assertEqual(repr(exc), "ImportError('test', path='somepath')")

exc = ImportError(name='somename', path='somepath')
self.assertEqual(repr(exc),
"ImportError(name='somename', path='somepath')")

exc = ImportError('test', name='somename', path='somepath')
self.assertEqual(repr(exc),
"ImportError('test', name='somename', path='somepath')")

Copy link
Member

@ezio-melotti ezio-melotti Mar 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are there any tests that ensure that the name of the module and the path are set correctly?
I would add a test tries to import a non-existing module and check those attributes (and/or they repr).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, a test with the ModuleNotFoundError subclass would be nice.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure, but we might want a test that actually tries importing some nonexistent module and see if its __repr__ has those required attributes.

def test_copy_pickle(self):
for kwargs in (dict(),
dict(name='somename'),
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_httplib.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ def test_status_lines(self):

def test_bad_status_repr(self):
exc = client.BadStatusLine('')
self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
self.assertEqual(repr(exc), '''BadStatusLine("''")''')

def test_partial_reads(self):
# if we have Content-Length, HTTPResponse knows when to close itself,
Expand Down
18 changes: 9 additions & 9 deletions Lib/test/test_yield_from.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ def g2(v = None):
"Yielded g2 spam",
"Yielded g2 more spam",
"Finishing g2",
"g2 returned StopIteration(3,)",
"g2 returned StopIteration(3)",
"Yielded g1 eggs",
"Finishing g1",
])
Expand Down Expand Up @@ -696,15 +696,15 @@ def g(r):
"g starting",
"f resuming g",
"g returning 1",
"f caught StopIteration(1,)",
"f caught StopIteration(1)",
"g starting",
"f resuming g",
"g returning (2,)",
"f caught StopIteration((2,),)",
"f caught StopIteration((2,))",
"g starting",
"f resuming g",
"g returning StopIteration(3,)",
"f caught StopIteration(StopIteration(3,),)",
"g returning StopIteration(3)",
"f caught StopIteration(StopIteration(3))",
])

def test_send_and_return_with_value(self):
Expand Down Expand Up @@ -741,17 +741,17 @@ def g(r):
"f sending spam to g",
"g received 'spam'",
"g returning 1",
'f caught StopIteration(1,)',
'f caught StopIteration(1)',
'g starting',
'f sending spam to g',
"g received 'spam'",
'g returning (2,)',
'f caught StopIteration((2,),)',
'f caught StopIteration((2,))',
'g starting',
'f sending spam to g',
"g received 'spam'",
'g returning StopIteration(3,)',
'f caught StopIteration(StopIteration(3,),)'
'g returning StopIteration(3)',
'f caught StopIteration(StopIteration(3))'
])

def test_catching_exception_from_subgen_and_returning(self):
Expand Down
4 changes: 4 additions & 0 deletions Misc/NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ What's New in Python 3.7.0 alpha 1?
Core and Builtins
-----------------

- bpo-29999: repr() of ImportError now contains attributes name and path.
Standard repr() of BaseException with single argument no longer contains
trailing comma.

- bpo-29914: Fixed default implementations of __reduce__ and __reduce_ex__().
object.__reduce__() no longer takes arguments, object.__reduce_ex__() now
requires one argument.
Expand Down
53 changes: 46 additions & 7 deletions Objects/exceptions.c
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,11 @@ BaseException_repr(PyBaseExceptionObject *self)
dot = (const char *) strrchr(name, '.');
if (dot != NULL) name = dot+1;

return PyUnicode_FromFormat("%s%R", name, self->args);
if (PyTuple_GET_SIZE(self->args) == 1)
return PyUnicode_FromFormat("%s(%R)", name,
PyTuple_GET_ITEM(self->args, 0));
else
return PyUnicode_FromFormat("%s%R", name, self->args);
}

/* Pickling support */
Expand Down Expand Up @@ -682,6 +686,30 @@ ImportError_str(PyImportErrorObject *self)
}
}

static PyObject *
ImportError_repr(PyImportErrorObject *self)
{
int hasargs = PyTuple_GET_SIZE(((PyBaseExceptionObject *)self)->args) != 0;
PyObject *r = BaseException_repr((PyBaseExceptionObject *)self);
if (r && (self->name || self->path)) {
/* remove ')' */
Py_SETREF(r, PyUnicode_Substring(r, 0, PyUnicode_GET_LENGTH(r) - 1));
if (r && self->name) {
Py_SETREF(r, PyUnicode_FromFormat("%U%sname=%R",
r, hasargs ? ", " : "", self->name));
hasargs = 1;
}
if (r && self->path) {
Py_SETREF(r, PyUnicode_FromFormat("%U%spath=%R",
r, hasargs ? ", " : "", self->path));
}
if (r) {
Py_SETREF(r, PyUnicode_FromFormat("%U)", r));
}
}
return r;
}

static PyObject *
ImportError_getstate(PyImportErrorObject *self)
{
Expand Down Expand Up @@ -744,12 +772,23 @@ static PyMethodDef ImportError_methods[] = {
{NULL}
};

ComplexExtendsException(PyExc_Exception, ImportError,
ImportError, 0 /* new */,
ImportError_methods, ImportError_members,
0 /* getset */, ImportError_str,
"Import can't find module, or can't find name in "
"module.");
static PyTypeObject _PyExc_ImportError = {
PyVarObject_HEAD_INIT(NULL, 0)
"ImportError",
sizeof(PyImportErrorObject), 0,
(destructor)ImportError_dealloc, 0, 0, 0, 0,
(reprfunc)ImportError_repr, 0, 0, 0, 0, 0,
(reprfunc)ImportError_str, 0, 0, 0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
PyDoc_STR("Import can't find module, or can't find name in "
"module."),
(traverseproc)ImportError_traverse,
(inquiry)ImportError_clear, 0, 0, 0, 0, ImportError_methods,
ImportError_members, 0, &_PyExc_Exception,
0, 0, 0, offsetof(PyImportErrorObject, dict),
(initproc)ImportError_init,
};
PyObject *PyExc_ImportError = (PyObject *)&_PyExc_ImportError;

/*
* ModuleNotFoundError extends ImportError
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy