Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variables of caller function in Python

My suspicion is that what I want to do isn't quite doable in a clean way in Python. Here are a few nested functions that call each other. (In general, they don't have to be lexically scoped, but need to dynamically call each other.)

def outer() :
    s_outer = "outer\n"

    def inner() :
        s_inner = "inner\n"
        do_something()

    inner()

Now when I call do_something() then I'd like to access the variables of the calling functions further up the callstack, in this case s_outer and s_inner.

Unfortunately, the nonlocal keyword here helps me only if I define do_something() inside of the inner() function. However, if I define it at the same level as outer() then the nonlocal keyword won't work.

However, I want to call do_something() from various other functions, but always execute it in their respective context and access their respective scopes.

Feeling naughty I then wrote a small accessor that I can call from within do_something() like this:

def reach(name) :
    for f in inspect.stack() :
        if name in f[0].f_locals : return f[0].f_locals[name]
    return None 

and then

def do_something() :
    print( reach("s_outer"), reach("s_inner") )

works just fine.

My two questions are these

  1. Is there a better way to solve this problem? (Other than wrapping the respective data into dicts and pass these dicts explicitly to do_something())

  2. Is there a more elegant/shortened way to implement the reach() function?

Cheers!

like image 930
Jens Avatar asked Mar 25 '13 06:03

Jens


People also ask

How do you access a variable inside a function in Python?

The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name. If you want to use that variable outside the method or class, you have to declared that variable as a global.

How do you extract a variable from a function in Python?

Using the return statement to get variable from function in Python. The return statement in Python is used to return some value from a function in Python. Since we cannot access the variable defined within the function from the outside, we can return it using the return statement to get variable from function in Python ...

How do you access a variable outside a function in Python?

1 Answer. Using the keyword "global", you can change the scope of a variable from local to global, and then you can access it outside the function.


1 Answers

There is no and, in my opinion, should be no elegant way of implementing reach since that introduces a new non-standard indirection which is really hard to comprehend, debug, test and maintain. As the Python mantra (try import this) says:

Explicit is better than implicit.

So, just pass the arguments. You-from-the-future will be really grateful to you-from-today.

like image 133
bereal Avatar answered Sep 30 '22 20:09

bereal