Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot change global variables in a function through an exec() statement?

Tags:

Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem:

 >>> myvar = 'test' >>> def myfunc(): ...     global myvar ...     exec('myvar = "changed!"') ...     print(myvar) ...  >>> myfunc() test >>> print(myvar) test 
like image 647
linkmaster03 Avatar asked Jan 18 '10 01:01

linkmaster03


1 Answers

Per the docs, the exec statement takes two optional expressions, defaulting to globals() and locals(), and always performs changes (if any) in the locals() one.

So, just be more explicit/specific/precise...:

>>> def myfunc(): ...   exec('myvar="boooh!"', globals()) ...  >>> myfunc() >>> myvar 'boooh!' 

...and you'll be able to clobber global variables to your heart's contents.

like image 141
Alex Martelli Avatar answered Oct 19 '22 11:10

Alex Martelli