Skip to content
Advertisement

Why isn’t the ‘global’ keyword needed to access a global variable?

From my understanding, Python has a separate namespace for functions, so if I want to use a global variable in a function, I should probably use global.

However, I was able to access a global variable even without global:

JavaScript

Why does this work?


See also UnboundLocalError on local variable when reassigned after first use for the error that occurs when attempting to assign to the global variable without global. See Using global variables in a function for the general question of how to use globals.

Advertisement

Answer

The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.

JavaScript

The above will give you:

JavaScript

While if you use the global statement, the variable will become available “outside” the scope of the function, effectively becoming a global variable.

JavaScript

So the above code will give you:

JavaScript

In addition, due to the nature of python, you could also use global to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement