3

To change a global variable inside a function we could proceed as follow:

let's say the global variable has 'x' as a name:

def change_x_globally( new_value ):
    global x 
    x = new_value

such an approach requires to hardcode the name of the variable beforehand, in case of multiple global variables this approach becomes cumbersome and unpractical

so I would input the name of the global variable e.g: if we wanted to change x we would input the string "x"

hence the desired final function would have the following signature:

def change_global_variable( variable_name, new_value ):
    pass

any ideas?

rachid el kedmiri
  • 2,376
  • 2
  • 18
  • 40

2 Answers2

3

You can use globals() to get back a dictionary of your globals, which you then address by string, e.g., globals()['x'] = new_value

Wolf
  • 4,254
  • 1
  • 21
  • 30
1

You should not change global values from within a function. If you want to do that, use either a global dict as proposed by @chepner or use a class.

dict idea:

values = {"x":0,"y":1}
def test(5):
    values["x"]=5

class idea:

class Values:
    x = 0
    y = 0
    # possibility one: class gets instantiated and then the main method gets called
    def run(self): 
        self.x = 4

# possibility two: class doesn't get instantiated and the values are written two by module level functions
def test(v):
    Values.x = v 
MegaIng
  • 7,361
  • 1
  • 22
  • 35