Python - Easiest way to define multiple global variables

59,899

Solution 1

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!

Solution 2

You could just unpack the variables:

global x, y, z
x, y, z = 4, 5, 6

Solution 3

The globals() builtin function refers to the global variables in the current module. You can use it just like a normal dictionary

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

Repeat this for all you variables.

However, you most certainly shouldn't do that

Solution 4

If they are conceptually related one option is to have them in a dictionary:

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

But as it was commented in your question, this is not the best approach to handle the problem that generated this question.

Share:
59,899
Stephen Gelardi
Author by

Stephen Gelardi

Updated on August 07, 2020

Comments

  • Stephen Gelardi
    Stephen Gelardi over 3 years

    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;