backlinks to this page:
All variables that are defined outside a function (and outside a class), are global variables.
All variables that are defined inside a function (or inside a class) are local variables
Python has a
global statement to make a variable global, see also scope of variables
not to be confused with:
globals()- shows all global variables of the current module
To avoid the use of global reasons why not to use global you can either:
__init__function. All class variables can be accessed and modified from outside the class as well as from inside the class.
config.py) and import this module in all your modules. Put your variable declarations inside this module. You can access and change the values from other modules
A variable defined inside a function does not exist outside this function. But when you use
global variablename inside the function, the variable act like a global variable and exist outside the function… after you called the function.
# x is NOT defined yet >>>def make_x(): x = 42 >>>x # will throw error NameError: name 'x' is not defined >>>make_x() # function call >>>x # will still throw error NameError: name 'x' is not defined >>>def make_y(): global y y = 42 >>>y # error, because y is not yet defined NameError: name 'y' is not defined >>>make_y() # function call >>>y 42
The correct way for a function to make a local variable into a global one is to have a