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
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()
)
Is there a more elegant/shortened way to implement the reach()
function?
Cheers!
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.
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 ...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With