The compile()
function is used to compile a source string into a code object. A source string refers to a regular string that contains valid Python code.
The function takes a source string and returns a code object that can be executed by using either exec()
or eval()
functions.
The compile function takes 3 required arguments: source
, filename
and mode
.
compile(source, filename, mode)
The source
argument is a string containing the Python source code to be compiled.
The filename
argument is a string representing the filename (if any) from which the code was read, if not provided, it defaults to '<string>'
.
Lastly, the mode
is a string specifying what kind of code object should be created, it is one of 'exec'
, 'eval'
or 'single'
.
code_string = "x = [1, 2, 3]\nprint(x)"
exec_code_object = compile(code_string, '', 'exec')
exec(exec_code_object)
code_string2 = "7 *(8 + 9)"
eval_code_object = compile(code_string2, '', 'eval')
print(eval(eval_code_object))
The difference between the 'exec' and the 'eval' mode is that, the exec mode is used with the exec()
function to execute a source string which can be having more than one statements while the 'eval' mode is used with the eval()
function which is only capable of evaluating a single expression.
The 'single' mode is used to compile a single interactive statement into a code object, this object can then be executed using either exec()
or eval()
functions.
single mode
code_string = "print('Hello, World!')"
single_code_object = compile(code_string, '', 'single')
exec(single_code_object)
code_string2 = "1 + 2 + 3"
single_code_object2 = compile(code_string2, '', 'single')
print(eval(single_code_object2))