Recently, I understand the concept of closing a function.
def outer(): somevar = [] assert "somevar" in locals() and not "somevar" in globals() def inner(): assert "somevar" in locals() and not "somevar" in globals() somevar.append(5) return somevar return inner function = outer() somevar_returned = function() assert id(somevar_returned) == id(function.func_closure[0].cell_contents)
As I understand it, the goal of closing a function is to keep an active reference to an object in order to avoid garbage collection of this object. This is why the following works perfectly:
del outer somevar_returned_2 = function() assert id(somevar_returned) == id(function.func_closure[0].cell_contents) assert id(somevar_returned) == id(somevar_returned_2)
The thing (always, as I understand it) before executing the inner function, Python rebuilds the locals variable dictionary. This dictionary will contain:
- function closure names associated with their cell contents
- function parameter names associated with their default value or a given parameter (and it can overwrite use case names)
The question is, where does Python store the closure name binding? I canโt find anything.
Note: function attributes:
>>> print "\n".join("%-16s : %s" % (e, getattr(function, e)) for e in dir(function) if not e.startswith("_") and e != "func_globals") func_closure : (<cell at 0x2b919f6bc050: list object at [...]>,) func_code : <code object inner at [...], file "<stdin>", line 4> func_defaults : None func_dict : {} func_doc : None func_name : inner
source share