3
$\begingroup$

Found this example on StackExchange:

foo = "bar"
exec(foo + " = 'something else'")
print(bar)

Should print:

something else

Blender (2.73) gives an error that bar is not defined. Can this still be done in Blender?

EDIT: This actually works in a blank file. What doesn't work is:

class testThis():
    def printMe(self):
        foo = "bar"
        exec(foo + " = 'something else'")
        print(bar)

test = testThis()
test.printMe()

Result:

NameError: name 'bar' is not defined

So I'm not sure if it's Blender related.

$\endgroup$
1
  • $\begingroup$ I'm voting to close this question as off-topic because it belongs on Stack Overflow, as the problem is with Python itself, not with Blender. $\endgroup$ Feb 20, 2015 at 16:03

2 Answers 2

2
$\begingroup$

It's a scope issue. Your exec() does not change the global or method-local scope. Instead, you need to pass two dictionaries to capture the sandboxed global and local scope:

class testThis:
    def printMe(self):
        foo = "bar"
        global_scope = {}
        local_scope = {}
        exec(foo + " = 'something else'", global_scope, local_scope)

        print(local_scope)
        # {'bar': 'something else'}

test = testThis()
test.printMe()
$\endgroup$
1
  • $\begingroup$ Sorry about the delay for marking as correct answer, been on vacation. Thanks a lot! $\endgroup$
    – bortran
    Mar 9, 2015 at 7:25
2
$\begingroup$

Official build of Blender come with the latest of Python (3.4.2 as of Blender 2.73); this means that your code cannot compile/be interpreted since, when moving to version 3.0, Python changed print from a keyword to a function.

Your code should be:

foo = "bar"
exec(foo + " = 'something else'")
print(bar) #Print is now a function; must use function call syntax.
$\endgroup$
4
  • $\begingroup$ You're right, I copied the code from the StackExchange post instead of my code and overlooked the print issue. Still, the result is, that "bar isn't defined". $\endgroup$
    – bortran
    Feb 20, 2015 at 13:12
  • 1
    $\begingroup$ @bortran It works fine for me... Are you sure you didn't misspell something, or something like that? Could you post your actual code? $\endgroup$ Feb 20, 2015 at 13:42
  • $\begingroup$ Works fine for me too in 2.73a on Windows. $\endgroup$
    – CodeManX
    Feb 20, 2015 at 14:24
  • $\begingroup$ Have you tried the updated code with the class? I copy that 1:1 into a blank text file in 2.73 on Windows and get the error. Just tried again. $\endgroup$
    – bortran
    Feb 20, 2015 at 15:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .