Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflect / Inspect closed-over variables in Python

If I have:

def f(x):
  def g(y):
    return x + y
  return g

f2 = f(2)

Is there a way to find the x binding that f2 will use? I looked at inspect but could not tell if some of the frame stuff would apply. In other words, could I define a closed_vars() below:

def closed_vars(anF):
    ... return ...

assert closedVars(f2) == {'x': 2}
like image 301
Des Avatar asked Oct 17 '13 01:10

Des


People also ask

What is __ closure __ in Python?

A closure is a function object that remembers values in enclosing scopes even if they are not present in memory. The __closure__ attribute of a closure function returns a tuple of cell objects. This cell object also has an attribute called cell_contents, which returns returns the contents of the cell.

Does Python allow closures?

Python Decorators make an extensive use of closures as well. On a concluding note, it is good to point out that the values that get enclosed in the closure function can be found out. All function objects have a __closure__ attribute that returns a tuple of cell objects if it is a closure function.

What is inspect stack in Python?

inspect. stack() returns a list with frame records. In function whoami() : inspect. stack()[1] is the frame record of the function that calls whoami , like foo() and bar() . The fourth element of the frame record ( inspect.


1 Answers

You don't have to use the inspect module here.

>>> dict(zip(f2.func_code.co_freevars, (c.cell_contents for c in f2.func_closure)))
{'x': 2}

works in Python 2.7

like image 191
Leonardo.Z Avatar answered Oct 16 '22 19:10

Leonardo.Z