4

I'm trying to convert a String containing a Python variable assignment into an actual variable.

The following was working for me.

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

But then when places this code in a function, VAR never gets defined.

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

    myFunction()    

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

Responses to a few of the questions...

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

Using: Python 3

4
  • This is usually a really bad idea. Can I ask what you're using this for? Commented Sep 10, 2015 at 22:38
  • What's the error message? Commented Sep 10, 2015 at 22:38
  • @PeterWood It's "NameError: name 'VAR' is not defined" Commented Sep 10, 2015 at 22:38
  • @Brett, you are using Python 3, correct? Commented Sep 10, 2015 at 22:39

3 Answers 3

2

You can also pass globals to exec:

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

related

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

Comments

2

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]

3 Comments

I suspect the OP is using Python 3, where exec is a function.
Is there any official documentation of this behavior? I noticed that depending whether one uses VAR later, exec decides on inserting it into locals() (perculiar: if one uses it, exec does not insert it into locals())
@WarrenWeckesser The OP uses exec(s) which is a function call.
1

In Python 2.7 you can simply do:

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

If you need custom namespace do:

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

Similar applies for Python 3 but exec there is actually a function so exec(...) is to be used. For example:

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

When you use functions scope comes into play. You can use locals(), globals() or use your custom namespace:

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

>>foo()
55

1 Comment

And damn it I type slow! Started typing first and finished last. LOL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.