8steve8
8steve8

Reputation: 2303

using exec() with python 3.2

so normally if i run these script with this code:

x=5
exec("x+=1")
output=str(x)

If I execute the above in a python console, output has a value of "6" But if it's run inside a function, the exec doesn't change the value of x.

Why does this happen, and how could I get the same behavior in a function as i do in the console?

Upvotes: 0

Views: 2375

Answers (1)

Lennart Regebro
Lennart Regebro

Reputation: 172239

WSGI has nothing to do with it. Your test that works is not running the same or even similar code. Here is your WSGI code made into non-WSGI:

>>> def app():
...     x=5
...     exec("x+=1")
...     print(x)
... 
>>> app()
5

As you see, it also doesn't change x. The code that did was this:

>>> x=5
>>> exec("x+=1")
>>> print(x)
6

The difference is that in one case it's global, in the other case local. From the documentation: "modifications to the default locals dictionary should not be attempted."

You can change a global by doing this:

x=5
def app():
    exec("global x;x+=1")
    print(x)

app()

And you can change a local by doing it explicitly:

def app():
    x=5
    d = {'x': x}
    exec("x+=1", d)
    x = d['x']
    print(x)

app()

If you have many locals you need access to, you can use d=locals().copy().

Upvotes: 7

Related Questions