Converting a string containing text to assign a Python variable to an actual variable

I am trying to convert a string containing the assignment of a Python variable to an actual variable.

The following worked for me.

    s = "VAR = [1,55]"
    exec(s)
    print(VAR)

But then, when it puts this code in a function, VAR is never defined.

    def myFunction():
        s = "VAR = [1,55]"
        exec(s)
        print(VAR)

    myFunction()    

I'm not sure what I am missing. Thanks in advance for your help!

Answers to a few questions ...

Error message: "NameError: name" VAR "not defined"

Usage: Python 3

+4
source share
3 answers

You can also pass exec global variables:

def myFunction():
    s = "VAR = [1,55]"
    exec(s, globals())
    print(VAR)

+2
source

python 2.7

def myfunc():
    v1 = 11
    exec "v1 = 22"
    print v1

myfunc() # 22

def myFunction():
    VAR = None
    s = "VAR = [1,55]"
    exec(s)
    print(VAR)

myFunction() # [1, 55]

OR

def myFunction():
    #VAR = None
    s = "VAR = [1,55]"
    exec(s)
    print(locals()["VAR"])

myFunction() # [1,55]
+2
source

Python 2.7 :

>> s = "VAR=55"
>> exec(s)
>> VAR
55

, :

>> my_ns = {}
>> exec "VAR=55" in my_ns
>> my_ns["VAR"]
55

Python 3, exec , exec(...) . :

>> s = "VAR=55"
>> exec(s)
>> VAR
55

When you use the functionality comes into play. You can use locals(), globals()or use your own namespace:

>>def foo():
    ns = {}
    s = "VAR=55"
    exec(s) in ns
    print(ns["VAR"])

>>foo()
55
+1
source

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


All Articles