I am trying to look for an easy way to define multiple global variables from inside a function or class.
The obvious option is to do the following:
global a,b,c,d,e,f,g...... a=1 b=2 c=3 d=4 .....
This is a simplified example but essentially I need to define dozens of global variables based on the input of a particular function. Ideally I would like to take care of defining the global name and value without having to update both the value and defining the global name independently.
To add some more clarity.
I am looking for the python equivalent of this (javascript):
var a = 1 , b = 2 , c = 3 , d = 4 , e = 5;
The best way to set up a list of global variables would be to set up a class for them in that module. Hope that helps! Brilliant idea to use a Class variable to deal situation where global variable use is unavoidable.
You can declare Global list on the file/module level like: my_global_list = list() in Python. If you want to append to it inside a function you can use the global keyword.
While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.
The value of a global variable can be changed accidently as it can be used by any function in the program. If we use a large number of global variables, then there is a high chance of error generation in the program.
You could just unpack the variables:
global x, y, z x, y, z = 4, 5, 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With