Global variables are used in programming to share memory between different sections of an application, this allows for a range of functionality such as keeping track of resource use between classes, storing statistics about an application and much more. In Python, they are mainly used to share values between classes and functions.
Understanding global variables in Pythonlink
In Python, a conventional global variable is only used to share a value within classes and functions. A variable- once declared as a global within a function or class can then be modified within the segment.
num = 1
def increment():
global num
num += 1
The above code would allow the variable 'num' to be used within that function, whereas if you were to omit the global statement, it would be undefined.
If you were to attempt to use this logic to declare a global variable from another class however, it would not work as it would in other languages such as Java or C++.
For example, if we had one class with a variable that needed to be accessed from within another imported class, there would be no way for us to access this variable using the global keyword:
main.py
import test
num = 1
test.increment()
test.py
def increment():
global num
num += 1 # num here would still be undefined
As you can see above, even though we try to access 'num' as a global within the increment() function after it has been given a value in main.py, it will still not be defined and will result in an error.
Sharing global variables between files/modules in Pythonlink
Even though the global keyword is conventionally only used to access variables from within the same module, there are ways to use it in order to share variables between files. For example, we could take influence from PHP and create something similar to the "superglobals" variables.
To do this, you can create a new module specifically for storing all the global variables your application might need. For this you can create a function that will initialize any of these globals with a default value, you only need to call this function once from your main class, then you can import the globals file from any other class and use those globals as needed.
For example, let's create a function similar to the example above that will increment a global variable. For this we'll need 3 classes to prove the concept; a main class, a class containing our increment function and a class containing the globals.
globals.py
def initialize():
global num
num = 1
main.py
import globals
import test
if __name__ == "__main__":
globals.initialize()
print( globals.num ) # print the initial value
test.increment()
print( globals.num ) # print the value after being modified within test.py
test.py
import globals
def increment():
globals.num += 1
When we run main.py the output will be:
1
2
As you can see, once we've initialized the global variable in globals.py, we can then access 'num' as a property from any other module within the application and it will retain its value.
If you're having trouble understanding how this works, feel free to leave a comment below!
drtftrtf
@SydneyWayman_610PH indeed, you can pretty much share any variables in this manner, although it's not good practice to go overboard with it. Usually I use this method to share redis connections or configuration files across modules.
are dataframes considered variables too? would dataframe values calculated in one module/file be available in another module/file?
i left a comment but it was under the title python global variables
Do you technically need global num? What would be the difference between what you have and just: def initialize(): num = 1 I am doing the same thing in some of my code but I am not using global to declare it. Am I missing something?
@ZaratTaraz_PJVC1 Once initiated in your main class you can import globals.py into any other file and it will retain any values edited by any other file. If you want a per-user variable you can simply create a dictionary variable in globals.py with the key being the user's session ID and the value being their session object
I have a problem. What if I want the variable to be updated by user input and made calculations in 1 file and displayed in 2nd file and the whole process in a loop. Just like _SESSION variable in php. Please help.
@PeterSaunders_96NTK You are more than welcome! If you have any suggestions for any other topics you would like me to cover then feel free to let me know!
I also signed up to thank you for this excellent explanation. I have spent hours googling this topic (among others!) as I try to teach myself Python programming! Even as a very competent, but now very old (!) and long-time-out-of practice programmer, I have been unable to make any sense of 99% of the answers I have found! The brevity and clarity of your description with the simple, clear example is exactly what I needed! Many thanks. Now I just need to work out how to use this site to find any other pearls of wisdom you have posted :O
Concise, clear, effective - thank you. Solved a BIG problem for me