1

My python is doing something weird. I'm trying to execute a bit of code from string form using exec/eval/compile. Specifically exec, but's failing silently with a syntax error so I switched to a eval instead.

#start of document

print( compile( 'Test_val = 1;', 'None', 'eval' ) )

Traceback (most recent call last):
  File "/Users/lucasyoung/Desktop/Application/__init__.py", line 6, in <module>
    print( compile( 'Test_val = 1;', 'None', 'eval' ) )
  File "None", line 1
    Test_val = 1;
             ^

I did a bit of testing, and I can, for example, call a print statement via compile. I can call variables into existence, but I can't seem to be able to name them. And whats strange is that this is within the scope of the compiled code's own context.

I know that stack has a big insistence on hyper detailing questions, but I honestly just don't know what to say about this one. Exec is supposed to fire some code from a string. The code I'm calling is perfectly valid. I'm stumped.

Lucas Young
  • 119
  • 1
  • 9

1 Answers1

3

Firstly there is a difference between eval() and exec()

eval() : The eval() method returns the result evaluated from the expression.

The eval function does the same for a single expression, and returns the value of the expression:

exec() : The exec() doesn't return any value, it returns None.

The exec function (which was a statement in Python 2) is used for executing a dynamically created statement or program:

therefore

eval('Test_val = 1;') is not a valid expression for eval.

exec('test_val = 1;') is a valid expression for exec

for in your case , you should use

print( compile( 'Test_val = 1;', 'None', 'exec' ) )

please check What's the difference between eval, exec, and compile? for more information

roshan ok
  • 383
  • 1
  • 6