Reputation: 39
I want to modify a global variable from a function in Python 2.7
x = 0
def func():
global x
x = 2
If I load this code in the interpreter, and then run func(), x remains 0. How do I modify the value of x from within a function?
EDIT: Here's a screenshot of the interpreter and source code. I'm not sure why it works for others and not for me. http://img18.imageshack.us/img18/9567/screenshotfrom201304222.png
Upvotes: 1
Views: 226
Reputation: 9084
This is a very interesting situation. When I ran your code from an interpreter with from mytest import *
I encountered the same issue:
>>> from mytest import *
>>> x
0
>>> func()
>>> x
0
However, when I just did import mytest
and ran it from there:
>>> import mytest
>>> mytest.x
0
>>> mytest.func()
>>> mytest.x
2
It turned out fine! The reason, I believe, comes from a line in http://docs.python.org/2/reference/simple_stmts.html#the-global-statement:
Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.
Looks like because it is a parameter in your import statement (by importing all), global
is having trouble with it. Do you need to import *
, or can you simply import the module whole?
Upvotes: 1