Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

scope

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()
like image 471
Max Ghenis Avatar asked Sep 01 '25 15:09

Max Ghenis


2 Answers

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.

like image 141
juanpa.arrivillaga Avatar answered Sep 04 '25 04:09

juanpa.arrivillaga


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
like image 40
heemayl Avatar answered Sep 04 '25 05:09

heemayl