TransWikia.com

How to change n distinct global variable using function with parameters in python?

Stack Overflow Asked by Pratik Goud on September 13, 2020

def change(a):
   a=4
print('1:')
c=3
print('Value before changing',c)
change(c)
print('Value after changing',c)
print('2:')
d=6
print('Value before changing',d)
change(d)
print('Value after changing',d)
print('3:')
e=7
print('Value before changing',e)
change(e)
print('Value after changing',e)

I want to change n distinct global variables. Eg: I want to change c,d and e global variables using function by passing it as a argument. How can I do so?

3 Answers

I've updated my previous answer so that it should work, but here is an alternative method.

def change(**kwargs):
    for name in kwargs:
        globals()[name] = 4

x = 3
change(x=x) # whatever follows the '=' sign is redundant in this case

Or, you could do

def change(**kwargs):
    globals().update(kwargs)

x = 3
change(x=4) # the global value of 'x' is now 4

Answered by Marcus Weinberger on September 13, 2020

the global keyword tells the function that there already exists a variable of this name, defined outside the current scope. It is in, what python calls, the global scope (think the outter-most scope of a python file).

>>> def change(a, value=4):
        global a
        a = value

>>> x = 3
>>> change(x)
# x = 4 

Answered by rnath on September 13, 2020

Edit:

My original answer wouldn't have worked. So here's my new answer. First, you'll need a function to get the name of the variable. This can be done with the builtin inspect package like so,

import inspect

def retrieve_name(var):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return [var_name for var_name, var_val in callers_local_vars if var_val is var]

Then, you'll need to rewrite your change function to

def change(a):
    globals()[a] = 4

And use it in conjunction with the retrieve_name function like so,

change(retrieve_name(x)[0])

Because if you just put the retrieve_name inside change it will always return a.

Below is my original answer:

Tell the function change that a is global. Eg:

def change(a):
  global a
  a = 4

Answered by Marcus Weinberger on September 13, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP