Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Easiest way to define multiple global variables

Tags:

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; 
like image 750
Stephen Gelardi Avatar asked Dec 06 '16 10:12

Stephen Gelardi


People also ask

How do you declare more than one global variable in Python?

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.

How do you declare a global list in Python?

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.

Should you avoid using global variables in Python?

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.

Is it better to use more number of global variables?

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.


1 Answers

You could just unpack the variables:

global x, y, z x, y, z = 4, 5, 6 
like image 170
d3x Avatar answered Sep 27 '22 17:09

d3x