exec inside functions in Python 3

Steven D'Aprano steve at pearwood.info
Tue Mar 22 08:57:56 EDT 2016


Anyone have any idea what is going on here?


def test():
    spam = 1
    exec("spam = 2; print('inside exec: %d' % spam)")
    print('outside exec: %d' % spam)


In Python 2.7:

py> test()
inside exec: 2
outside exec: 2



In Python 3.4:

outside exec: 1
py> test()
inside exec: 2
outside exec: 1



What happened to spam?



-- 
Steven




More information about the Python-list mailing list