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  the exec() or eval() functions. The 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 for example, "print('Hello, World!')". The filename argument is a string representing the filename (if any) from which the code was read, this argument is optional, 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'.

Example 1: 
code_string = "x = [1, 2, 3]\nprint(x)"
exec_code_object = compile(code_string, '', 'exec')
exec(exec_code_object)
//[1, 2, 3]
code_string2 = "7 *(8  + 9)"
eval_code_object = compile(code_string2, '', 'eval')
eval(eval_code_object)
//119

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. example:

code_string = "print('Hello, World!')"
single_code_object = compile(code_string, '', 'single')
exec(single_code_object)
//Hello, World!
code_string2 = "1 + 2 + 3"
single_code_object2 = compile(code_string2, '', 'single')
eval(single_code_object2)
//6