1

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

3
  • 7
    This works as-is for me. Are you sure you've called the function? I paste your code in, call func(), and print x. I get 2. Commented Apr 23, 2013 at 2:35
  • What are you talking about? It still works. Commented Apr 23, 2013 at 2:35
  • You could try printing all globals() in func() to see if x is included. Commented Apr 23, 2013 at 4:39

1 Answer 1

1

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?

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

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.