2

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?

1
  • Almost anything is possible, but things like this are never a good idea (obviously, there are exceptions, but the people who can decide that don't have to ask how it's done -- not necessarily vice versa though). Commented May 3, 2012 at 16:58

4 Answers 4

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

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! Can you explain why my version didn't work? I suspect that there is something wrong with the exec's context.
@user1084871: So do I, but I can't quite put my finger on it.
4

yes, you can use globals() for that:

globals()['whatever'] = 123

(and it's good that you realise yourself that this isn't a very good style)

Comments

2

Use the globals function

globals()[varname] = value

The globals function returns a dict containing the module's global variables.

Comments

1

You could, see the other answers.

But you really should not.

It's not that global variables are automatically a bad idea; the bigger problem is that looking at a plain call to f() or f(x), you have no idea you just modified your local (that is, in this case, global) scope.

def f():
    return 1

x = f()
print x

does exactly the same, but documents what's going on in the scope inside that scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.