Max Ghenis
Max Ghenis

Reputation: 15803

Access a variable by name defined in a parent function from a nested function

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()

Upvotes: 4

Views: 1629

Answers (3)

heemayl
heemayl

Reputation: 42017

I'm not really sure about it's usefullness, but you can do this by inspecting the stack frame of the enclosing function i.e. frame at depth 1 and getting x from the locals dict:

In [1]: import sys

In [2]: def f():
   ...:     x = 1
   ...:     def g():
   ...:         print(sys._getframe(1).f_locals['x'])
   ...:     g()
   ...:    
In [3]: f()
1

Upvotes: 2

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95957

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.

Upvotes: 6

t_warsop
t_warsop

Reputation: 1270

Why not just pass the value to the child function like this:

def f(): 
    x = 1 
    def g(parameter): 
        print(parameter) 
    g(x)

Upvotes: 0

Related Questions