The global Declaration
What if you really need to modify a value in the global scope from within a function? This is possible in Python using the
global declaration. In this example, the
global x statement indicates that while the function executes, references to the name
x refer to the
x in the global namespace.
As you have seen in an earlier lesson, the
globals() function returns a reference to the global namespace dictionary. That means you can just reassign a value to a variable in the global scope directly through the dictionary that is returned by the
globals() function, as you will see when you run the function and look at the current value of
x. There isn’t much reason to do it this way, since the
global declaration definitely makes the intent more clear.
Since a variable can be reassigned through the global namespace dictionary that is returned by the
globals() function and using the
global declaration has a similar behavior, you can also declare a new global variable within the function.
So when you try to call
y before calling the function, you will see it doesn’t exist yet in the global namespace. However, when you call the function and then call
y, you will see it is indeed created in the global namespace.
One thing to look out for when using the
global declaration is that it appears in the function before it is used. In this function, the value of
x is printed before the
global declaration, which will throw a
Become a Member to join the conversation.