From e968bc735794a7123f28f26d68fdf5dc8c845280 Mon Sep 17 00:00:00 2001 From: Thomas Kluyver Date: Tue, 24 Oct 2017 13:42:36 +0100 Subject: [PATCH] bpo-30639: Lazily compute repr for error (#2132) --- Lib/inspect.py | 5 +++-- Lib/test/test_inspect.py | 8 ++++++++ .../next/Library/2017-10-24-12-24-56.bpo-30639.ptNM9a.rst | 2 ++ 3 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2017-10-24-12-24-56.bpo-30639.ptNM9a.rst diff --git a/Lib/inspect.py b/Lib/inspect.py index 9a843d6420..6d6fde9ee4 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -662,8 +662,9 @@ def getfile(object): object = object.f_code if iscode(object): return object.co_filename - raise TypeError('{!r} is not a module, class, method, ' - 'function, traceback, frame, or code object'.format(object)) + raise TypeError('module, class, method, function, traceback, frame, or ' + 'code object was expected, got {}'.format( + type(object).__name__)) def getmodulename(path): """Return the module name for a given file, or None.""" diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 819fcc5853..e64215d467 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -463,6 +463,14 @@ class TestRetrievingSourceCode(GetSourceBase): with self.assertRaises(TypeError): inspect.getfile(C) + def test_getfile_broken_repr(self): + class ErrorRepr: + def __repr__(self): + raise Exception('xyz') + er = ErrorRepr() + with self.assertRaises(TypeError): + inspect.getfile(er) + def test_getmodule_recursion(self): from types import ModuleType name = '__inspect_dummy' diff --git a/Misc/NEWS.d/next/Library/2017-10-24-12-24-56.bpo-30639.ptNM9a.rst b/Misc/NEWS.d/next/Library/2017-10-24-12-24-56.bpo-30639.ptNM9a.rst new file mode 100644 index 0000000000..c6aeb2356f --- /dev/null +++ b/Misc/NEWS.d/next/Library/2017-10-24-12-24-56.bpo-30639.ptNM9a.rst @@ -0,0 +1,2 @@ +:func:`inspect.getfile` no longer computes the repr of unknown objects to +display in an error message, to protect against badly behaved custom reprs. -- 2.40.0