0

Given a string (e.g. "lista=[1,2,3]") I would like to be able to use the variable lista.

exec() does the work outside a function, but when used inside a function the variables cannot be used in that same function. I guess it has something to do with local and global variables but I don't really understand the problem.

For example,

def funcion(texto):
    exec(texto)
    print(lista)

funcion("lista = [3,4,5]")

Gives the error: NameError: name 'lista' is not defined.

1 Answers1

0

add globals

def funcion(texto):
    exec(texto, globals())
    print(lista)

funcion("lista = [3,4,5]")
It_is_Chris
  • 13,504
  • 2
  • 23
  • 41