Reading a parent's scope in python

Viewed 3640

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?

1 Answers
Related