开发者

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 pyth开发者_如何学Goon 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?


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜