Chris Real February 2016

Merging global and local scopes

If this works

x=5
def main():
    for globe in locals():
        globals().update(locals()[globe])
    print x
main()

then why doesn't this?

x=5
def main():
    for globe in locals():
        globals().update(locals()[globe])
    x+=1
    print x
main()

The error in the latter statement claims that x is referenced before assignment, however it works in the first example...

Answers


k4ppa February 2016

In python when you assign a variable the declaration happens automatically. So when you assign a value to x inside the function, python think that is a new local variable, shadowing the global x.

if you want to assign a value to the global x you can do this:

x=5
def main():
    global x

    x += 1
    print x
main()


alpha1554 February 2016

You cannot assign a global variable in python without explicitly doing so. By writing x+=1 you are assigning a value to x and are implicitly declaring x as a local variable. But it is not defined and therefore you get an error.

The loop has no actual effect, as the locals dictionary is empty.

If you want to use global variables in Python (which you shouldn't, but that's another matter), you should use the global keyword.


B. M. February 2016

suffixing 1 and 2 your two functions, you can find local names (syntax slightly different in python 2) :

In [7]: main1.__code__.co_varnames
Out[7]: ('globe',)

In [8]: main2.__code__.co_varnames
Out[8]: ('globe', 'x')

So x have different status. In the second case the local x mask the global one, so x=x+1 cause the error, because not yet defined.

From docs :

If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal or global.(...).If a variable is used in a code block but not defined there, it is a free variable.

Post Status

Asked in February 2016
Viewed 2,017 times
Voted 10
Answered 3 times

Search




Leave an answer