Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting variables with exec inside a function

I just started self teaching Python, and I need a little help with this script:

old_string = "didnt work"    new_string = "worked"  def function():     exec("old_string = new_string")          print(old_string)   function() 

I want to get it so old_string = "worked".

like image 376
Spacenaut Avatar asked Apr 19 '14 09:04

Spacenaut


People also ask

Can we declare global variable inside a function?

Global variables can be used by everyone, both inside of functions and outside.

What is exec () used for?

The exec command is a powerful tool for manipulating file-descriptors (FD), creating output and error logging within scripts with a minimal change. In Linux, by default, file descriptor 0 is stdin (the standard input), 1 is stdout (the standard output), and 2 is stderr (the standard error).

How do you execute a function inside python?

exec() in Python. exec() function is used for the dynamic execution of Python program which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed.

What does Exec return Python?

Python exec() does not return a value; instead, it returns None. A string is parsed as Python statements, which are then executed and checked for any syntax errors. If there are no syntax errors, the parsed string is executed. If it's an object code, then it is simply executed.


1 Answers

You're almost there. You're trying to modify a global variable so you have to add the global statement:

old_string = "didn't work" new_string = "worked"  def function():     exec("global old_string; old_string = new_string")     print(old_string)  function() 

If you run the following version, you'll see what happened in your version:

old_string = "didn't work" new_string = "worked"  def function():     _locals = locals()     exec("old_string = new_string", globals(), _locals)     print(old_string)     print(_locals)  function() 

output:

didn't work {'old_string': 'worked'} 

The way you ran it, you ended up trying to modify the function's local variables in exec, which is basically undefined behavior. See the warning in the exec docs:

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

and the related warning on locals():

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

like image 142
thebjorn Avatar answered Sep 22 '22 15:09

thebjorn