Python is an easy way to define multiple global variables

I am trying to find an easy way to define several global variables from within 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 specific function. Ideally, I would like to take care of defining the global name and value without having to update the value and define the global name independently.

To add more clarity.

I am looking for the python equivalent of this (javascript):

 var a = 1 , b = 2 , c = 3 , d = 4 , e = 5; 
+5
source share
3 answers

Well, I'm a newbie myself, and that was a big problem for me, and I think that this is related to the wording of the question (I formulated it the same way as when searching on Google and could not find an answer that related to the fact that I tried to do). Please someone correct me if there is a reason why I should not do this, but ...

The best way to customize the list of global variables is to set a class for them in this module.

 class globalBS(): bsA = "F" bsB = "U" 

Now you can call them, change them, etc. in any other function, referring to them as such:

 print(globalBS.bsA) 

will print "F" in any function of this module. The reason for this is because python treats classes as modules, so it works well for creating a list of global variables, for example, when trying to create an interface with several parameters, such as I'm doing now, without copying and pasting a huge list of globals in each function. I would just keep the class name as short as possible - perhaps one or two characters instead of a whole word.

Hope this helps!

+3
source

If they are conceptually connected, one of them should have them in the dictionary:

 global global_dictionary global_dictionary = {'a': 1, 'b': 2, 'c': 3} 

But since this was commented on in your question, this is not the best approach to solve the problem that gave rise to this question.

-1
source

The built-in function globals() refers to global variables in the current module. You can use it as a regular dictionary

 globals()['myvariable'] = 5 print(myvariable) # returns 5 

Repeat this for all variables.

However, you certainly should not do this.

-1
source

Source: https://habr.com/ru/post/1260863/


All Articles