diff --git a/Lib/inspect.py b/Lib/inspect.py index 8bb3a375735af6..d29910942f4077 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -1462,6 +1462,14 @@ def _formatannotation(annotation): return formatannotation(annotation, module) return _formatannotation +# A placeholder with as repr (using a string would have '' +# with quotes). This is used in formatargvalues function. +class _Deleted: + def __repr__(self): + return '' + +_deleted = _Deleted() +del _Deleted def formatargvalues(args, varargs, varkw, locals, formatarg=str, @@ -1476,7 +1484,7 @@ def formatargvalues(args, varargs, varkw, locals, argument is an optional function to format the sequence of arguments.""" def convert(name, locals=locals, formatarg=formatarg, formatvalue=formatvalue): - return formatarg(name) + formatvalue(locals[name]) + return formatarg(name) + formatvalue(locals.get(name, _deleted)) specs = [] for i in range(len(args)): specs.append(convert(args[i])) diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 92aba519d28a08..40c72cc7b2166f 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -477,6 +477,21 @@ def test_frame(self): self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), '(x=11, y=14)') + def return_current_frame(x): + return inspect.currentframe() + + self.assertEqual(inspect.formatargvalues(*inspect.getargvalues(return_current_frame(5))), "(x=5)") + self.assertEqual(inspect.formatargvalues(*inspect.getargvalues(return_current_frame(9))), "(x=9)") + + # See issue-61448 + def test_formatargvalues_deleted_args(self): + def fun(a, b, x, y): + del b, y + return inspect.currentframe() + + args = inspect.getargvalues(fun(2, 4, 8, 16)) + self.assertEqual(inspect.formatargvalues(*args), '(a=2, b=, x=8, y=)') + def test_previous_frame(self): args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back) self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f']) diff --git a/Misc/NEWS.d/next/Library/2023-01-26-09-36-24.gh-issue-61448.SOAkvt.rst b/Misc/NEWS.d/next/Library/2023-01-26-09-36-24.gh-issue-61448.SOAkvt.rst new file mode 100644 index 00000000000000..2c64d08b0e4b09 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-01-26-09-36-24.gh-issue-61448.SOAkvt.rst @@ -0,0 +1,2 @@ +Fix inspect.getargvalues function failing if arg name is not bound to a value. +Co-authored-by Ezio Melotti.