Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a parent's scope in python

Suppose I have a hierarchy of functions, I want to be able to access (not change!) the parents scope. Here is an illustrative example.

def f():
    a = 2
    b = 1
    def g():
        b = 2
        c = 1
        print globals() #contains a=1 and d=4
        print locals() #contains b=2 and c=1, but no a
        print dict(globals(), **locals()) #contains a=1, d=4 (from the globals), b=2 and c=1 (from g)
        # I want a=2 and b=1 (from f), d=4 (from globals) and no c
    g()
a = 1
d = 4
f()

Can I access f's scope from within g?

like image 535
Andy Hayden Avatar asked Jul 19 '12 12:07

Andy Hayden


1 Answers

In general, you can't in Python. If your Python implementation supports stack frames (CPython does), you could inspect the calling function's frame using the inspect module and extract the local variables, but I doubt this is the best solution for the problem you want to solve (whatever that might be). There is probabaly some flaw in your design if you think you need this.

Note that using inspect will enable you to go up in the call stack, not in the stack of lexical scopes. If you return g from f(), the scope of f will be gone, so there is no way at all to access it, since it does not even exist.

like image 81
Sven Marnach Avatar answered Sep 18 '22 21:09

Sven Marnach