0

I know, I know.. I shouldn't use exec() built-in function, it's not a good practice. However, I need to use it for a good reason (you can find the reason here: List to String to List Python 3. And you can suggest a better idea there). So, the problem is the following:

def function():
    exec("l = [1, 2, 3]")
    for i in l:
        print(i)

function()

Raise:

Traceback (most recent call last): File "", line 1, in function() File "", line 3, in function for i in l: NameError: name 'l' is not defined

Note that this is a simplified version, in this example the use of exec() seems unnecessary but in the real case it's not. Any ideas? Thanks!

EDIT

The answer can be found and very well discussed in Behavior of exec function in Python 2 and Python 3

A working code for the problem is the following:

def function():
    d = locals()
    exec("l = [1, 2, 3]", globals(), d)
    for i in d['l']:
        print(i)

function()

Thanks to @Martijn Pieters

Community
  • 1
  • 1
Martin DLF
  • 231
  • 2
  • 3
  • 7

0 Answers0