exec()
Syntax:
1exec(object[, globals[, locals]])
2
3:param object: As already said this can be a string or object code
4:param globals: This can be a dictionary and the parameter is optional
5:param locals: This can be a mapping object and is also optional
eg.
1from math import *
2exec("print(factorial(5))", {"factorial":factorial})
eval()
Syntax:
1eval(expression[, globals[, locals]])
diff with exec()
1.eval accepts only a single expression, exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on. 2.eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).
1>>> a = 5
2>>> eval('37 + a') # it is an expression
342
4>>> exec('37 + a') # it is an expression statement; value is ignored (None is returned)
5>>> exec('a = 47') # modify a global variable as a side effect
6>>> a
747
8>>> eval('a = 47') # you cannot evaluate a statement
9Traceback (most recent call last):
10 File "<stdin>", line 1, in <module>
11 File "<string>", line 1
12 a = 47
13 ^
14SyntaxError: invalid syntax
compile()
Syntax:
1compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
It can be used to speed up repeated invocations of the same code with exec or eval by compiling the source into a code object beforehand.