Setting variables with exec inside a function

I just started learning Python myself, 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 like this old_string = "worked".

+17
source share
3 answers

You are almost there. You are trying to change a global variable, so you need to add an operator global:

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 will 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'}

As you launched it, you tried to change the local variables of the function in exec, which is essentially undefined behavior. See warning in execdocs :

: , locals() : . , , exec() .

locals():

: ; , .

+13

exec globals() .

>>> def function(command):
...    exec(command, globals())
...
>>> x = 1
>>> function('x += 1')
>>> print(x)
2

locals(), globals() , .

+4

I edited the question. I hope I understand this question well.

For this you can simply do

old_string = new_string
print(old_string)
"worked"

But I'm sure this is described in any textbook ...

-1
source

Source: https://habr.com/ru/post/1537185/


All Articles