Stephen Gelardi
Stephen Gelardi

Reputation: 565

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;

Upvotes: 38

Views: 95562

Answers (5)

Michael
Michael

Reputation: 1

count = 1
globe = {}
while count < 27:
    yy = chr(96 + count)
    xx = count
    globe[yy] = xx
    count += 1
print((globe))

Upvotes: 0

d3x
d3x

Reputation: 715

You could just unpack the variables:

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

Upvotes: 53

qui
qui

Reputation: 216

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!

Upvotes: 20

blue note
blue note

Reputation: 29081

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

Upvotes: 6

Martinbaste
Martinbaste

Reputation: 416

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.

Upvotes: 3

Related Questions