4

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()
8
  • 5
    x is neither a global nor a local variable. You'd have to inspect the stack frame. Honestly, there is almost certainly no reason to do this. What are you actually trying to accomplish? IOW, you can probably accomplish this, but you probably don't really want to. Commented Jul 11, 2019 at 7:29
  • @heemayl The context is looping through a set of variable names. It could probably be done better with a dict but I'm looking for a minimal refactor from existing code and am generally curious if it's possible. Commented Jul 11, 2019 at 7:33
  • Why not use a dictionary to define your variables as key, and perform dict lookup Commented Jul 11, 2019 at 7:38
  • As I said, I understand a dict would be better practice, but I'm curious if this is possible. Commented Jul 11, 2019 at 7:38
  • Why not go with the better practice, also x is not a local or a global variable in either of the two definitions, for the first def to work, x needs to be defined in a global scope, for the second def to work, x needs to be defined inside g Commented Jul 11, 2019 at 7:41

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

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

1 Comment

I need to access 'x' as a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.