Account for the possibility of closing over an undefined variable when getting a function's namespace.

PiperOrigin-RevId: 293210304
Change-Id: Ia16c9032c63a38106a38ba2039c274c4752a0b64
This commit is contained in:
Dan Moldovan 2020-02-04 13:03:06 -08:00 committed by TensorFlower Gardener
parent be4b1b795e
commit f61454bfc3
2 changed files with 20 additions and 1 deletions

View File

@ -166,7 +166,11 @@ def getnamespace(f):
freevars = six.get_function_code(f).co_freevars
if freevars and closure:
for name, cell in zip(freevars, closure):
namespace[name] = cell.cell_contents
try:
namespace[name] = cell.cell_contents
except ValueError:
# Cell contains undefined variable, omit it from the namespace.
pass
return namespace

View File

@ -253,6 +253,21 @@ class InspectUtilsTest(test.TestCase):
ns = inspect_utils.getnamespace(factory)
self.assertEqual(ns['free_function'], free_function)
def test_getnamespace_closure_with_undefined_var(self):
if False: # pylint:disable=using-constant-test
a = 1
def test_fn():
return a
ns = inspect_utils.getnamespace(test_fn)
self.assertNotIn('a', ns)
a = 2
ns = inspect_utils.getnamespace(test_fn)
self.assertEqual(ns['a'], 2)
def test_getnamespace_hermetic(self):
# Intentionally hiding the global function to make sure we don't overwrite