Question

I am aware of the fact that updating locals() or globals() should be avoided if possible. As far as I understand, updating locals() in a function normally results in a NameError when referencing an updated variable, as already discussed here:

How can I load all keys from a dict as local variables, a better aproach?

My understanding is that the interpreter creates a static lookup table for local variables, and thus changes to locals() and not visible at runtime.

How about updating globals() then? This doesn't seem to be a terribly great idea either. Why does the following code fail:

def foo():
    globals().update({'a': 1})
    print a
    if False: a = 0

>>> foo()
UnboundLocalError: local variable 'a' referenced before assignment

while removing the never-to-be-executed if False: a = 0 assignment works?

If the interpreter creates a look up table for performance reasons, shouldn't it take statements that will not be executed during runtime into account?

Was it helpful?

Solution

This has nothing to do with your update to the globals dict specifically. You'd get exactly the same result if you did this:

a = 1

def foo():
    print a
    if False: a = 0

foo()

That's because any assignment to a variable that's not explicitly marked as global within a scope makes the variable local throughout that scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top