diff --git a/Lib/inspect.py b/Lib/inspect.py index 81ea5372eec235f..591f6ae6846b6f3 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -1552,13 +1552,14 @@ def getclosurevars(func): code = func.__code__ # Nonlocal references are named in co_freevars and resolved # by looking them up in __closure__ by positional index - if func.__closure__ is None: - nonlocal_vars = {} - else: - nonlocal_vars = { - var : cell.cell_contents - for var, cell in zip(code.co_freevars, func.__closure__) - } + nonlocal_vars = {} + unbound_names = set() + if func.__closure__ is not None: + for var, cell in zip(code.co_freevars, func.__closure__): + try: + nonlocal_vars[var] = cell.cell_contents + except ValueError: + unbound_names.add(var) # Global and builtin references are named in co_names and resolved # by looking them up in __globals__ or __builtins__ @@ -1568,7 +1569,6 @@ def getclosurevars(func): builtin_ns = builtin_ns.__dict__ global_vars = {} builtin_vars = {} - unbound_names = set() global_names = set() for instruction in dis.get_instructions(code): opname = instruction.opname diff --git a/Lib/test/test_inspect/test_inspect.py b/Lib/test/test_inspect/test_inspect.py index ef9d2061611f335..789c78e5487b9f3 100644 --- a/Lib/test/test_inspect/test_inspect.py +++ b/Lib/test/test_inspect/test_inspect.py @@ -2274,6 +2274,17 @@ def check_y_combinator(func): {'x': 3}) Y(check_y_combinator) + def test_empty_nonlocal_cell(self): + def make_func(): + bound = 1 + value = None + func = lambda: (bound, value) + del value + return func + + expected = inspect.ClosureVars({'bound': 1}, {}, {}, {'value'}) + self.assertEqual(inspect.getclosurevars(make_func()), expected) + def test_getclosurevars_empty(self): def foo(): pass _empty = inspect.ClosureVars({}, {}, {}, set()) diff --git a/Misc/NEWS.d/next/Library/2026-11-18-18-58-33.gh-issue-162206.Ym4qL8.rst b/Misc/NEWS.d/next/Library/2026-11-18-18-58-33.gh-issue-162206.Ym4qL8.rst new file mode 100644 index 000000000000000..632e73d4c0a4bf2 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-18-18-58-33.gh-issue-162206.Ym4qL8.rst @@ -0,0 +1,2 @@ +Report empty closure cells as unbound in :func:`inspect.getclosurevars` +instead of raising :exc:`ValueError`. Patch by tonghuaroot.