Behavior of exec function in Python 2 and Python 3

前端 未结 4 1049
北海茫月
北海茫月 2020-11-22 08:34

Following code gives different output in Python2 and in Python3:

from sys import version

print(version)

def execute(a, st):
    b         


        
4条回答
  •  执笔经年
    2020-11-22 09:24

    I'm afraid I can't explain it exactly, but it basically comes from the fact that b inside the function is local, and exec() appears to assign to the global b. You'll have to declare b to be global inside the function, and inside the exec statement.

    Try this:

    from sys import version
    
    print(version)
    
    def execute1(a, st):
        b = 42
        exec("b = {}\nprint('b:', b)".format(st))
        print(b)
    
    def execute2(a, st):
        global b
        b = 42
        exec("global b; b = {}\nprint('b:', b)".format(st))
        print(b)
    
    a = 1.
    execute1(a, "1.E6*a")
    print()
    execute2(a, "1.E6*a")
    print()
    b = 42
    exec("b = {}\nprint('b:', b)".format('1.E6*a'))
    print(b)
    

    Which gives me

    3.3.0 (default, Oct  5 2012, 11:34:49) 
    [GCC 4.4.5]
    b: 1000000.0
    42
    
    b: 1000000.0
    1000000.0
    
    b: 1000000.0
    1000000.0
    

    You can see that outside the function, the global b is automatically picked up. Inside the function, you're printing the local b.

    Note that I would have thought that exec() always uses the global b first, so that in execute2(), you don't need to declare it inside the exec() function. But I find that doesn't work (which is the part I can't explain exactly).

提交回复
热议问题