Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Is it possible to create a global variable with the name given as string?

Tags:

python

scope

I can create a global variable in a function:

def f():
    global x
    x=1

f()
print x

But can I do the same if I only have the name of that variable in f()?

def f(varname):
    exec('global ' + varname)
    exec(varname + '=1')

f('x')
print x

This doesn't work - "name 'x' is not defined". Don't tell me that this is a terrible style of programming - I know that. The question is if this is possible to do in Python.

Thanks for the answers, but the question of why exec didn't work remains. Is is somehow executed in a different context? Is it a part of a different module, so that it creates a global variable in a different module?

like image 586
user1084871 Avatar asked Jul 23 '26 14:07

user1084871


1 Answers

In [1]: globals()['x'] = 42

In [2]: x
Out[2]: 42

It works the same way if done from within a function.

like image 163
NPE Avatar answered Jul 25 '26 04:07

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!