Home > Software engineering >  Is there a way to use exec inside a function?
Is there a way to use exec inside a function?

Time:10-24

The function:


def thefunction():
  exec("x = 'text'")
  return x
print(thefunction())

and it doesnt work... this is for python 3

CodePudding user response:

Give it a dict as a storage for variables.

def thefunction():
  vars = {}
  exec("x = 'text'", vars)
  return vars['x']

print(thefunction())

In any case, read the documentation and warnings about exec.

CodePudding user response:

you need to pass in your locals or it will only be local to that ...

def thefunction():
   my_locals = locals()
   exec("x = 'text'",globals(),my_locals)
   return my_locals['x']

print(thefunction())

you can make it a little safer by sending in an isolated environment... but the bottom line is that its not safe to exec untrusted input

  • Related