Journey to Master Python (WIP)

ageekymonk
1,038 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Eval, Exec and Compile

Eval

Eval is used to evaulate dynamically generated python expression. It cannot evaluate statements. For example eval('10+5') is valid but eval('a=5') is not valid. This means it cannot be used to evaluate function definition, loops etc. It returns last executed expression.

Exec

Exec is used to execute dynamically generated python code. It always returns None. It can execute any python code like loop, function, class etc.

Compile

This might seem odd for a interpreted language. But this is used to compile code into python bytecode. It is used to speed up the repeated execution of a code.

Eval Exec Compile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# eval
a = eval('100*200')
print(f'Value of a is {a}')
b = exec('a = 100*200')
print(f'Value of a is {a} b is {b}')
# compiling the code
eval_compiled_code = compile('100*200', '<string>', 'eval')
exec_compiled_code = compile('a = 100*200', '<string>', 'exec')
a = eval(eval_compiled_code)
b = exec(exec_compiled_code)
# This is the quirky part. Eval can run exec compiled code and returns value
eval(exec_compiled_code)
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content