0

The function:


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

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

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

7 Comments

It gives me NameError: name 'x' is not defined, in Python 3.10.8. It is valid to use globals() as the third argument, which writes the result to the global variable, then retrieves x from the global variable and returns it.
I just double checked ... it works perfectly in my interpretter ... (I did have globals and locals swapped earlier .... but that should not have resulted in a nameerror)
Did you delete x from the global variable and retest it? The local variable of the function is now implemented using an array. The document of exec never guarantees that it can work properly in the function...
@JoranBeasley you sure you are using Python 3?
@MechanicPig that's not true. It just won't modify the function's local namespace. But you can pass in your own namespace and it should work
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.