Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__
Expand All @@ -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
Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_inspect/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Report empty closure cells as unbound in :func:`inspect.getclosurevars`
instead of raising :exc:`ValueError`. Patch by tonghuaroot.
Loading