Search code examples
pythonvariablesglobal

Python - Easiest way to define multiple global variables


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;

Solution

  • Alright, I'm new myself and this has been a big issue for me as well and I think it has to do with the phrasing of the question (I phrased it the same way when googling and couldn't quite find an answer that was relevant to what I was trying to do). Please, someone correct me if there's a reason I should not do this, but...

    The best way to set up a list of global variables would be to set up a class for them in that module.

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

    now you can call them, change them, etc. in any other function by referencing them as such:

    print(globalBS.bsA)
    

    would print "F" in any function on that module. The reason for this is that python treats classes as modules, so this works out well for setting up a list of global variables- such as when trying to make an interface with multiple options such as I'm currently doing, without copying and pasting a huge list of globals in every function. I would just keep the class name as short as possible- maybe one or two characters instead of an entire word.

    Hope that helps!