Ad

Access A Variable By Name Defined In A Parent Function From A Nested Function

- 1 answer

Is there a way to use something like globals() or locals() to access a variable defined in a parent function by name (i.e., as a string)?

Both of these examples give KeyError: 'x':

def f(): 
    x = 1 
    def g(): 
        print(globals()['x']) 
    g()

def f(): 
    x = 1 
    def g(): 
        print(locals()['x']) 
    g()
Ad

Answer

Yes it's possible, but you are working against Python, don't do this:

In [1]: import inspect

In [2]: def f():
   ...:     x = 1
   ...:     def g():
   ...:         print(inspect.currentframe().f_back.f_locals['x'])
   ...:     g()
   ...:

In [3]: f()
1

Seriously, don't. Write good code, not bad code. For all of us.

Ad
source: stackoverflow.com
Ad