Difference between python built-in callable(), compile() and () function with practical example

Python callable() Function

A python callable() function in Python is something that can be called. This built-in function checks and returns true if the object passed appears to be callable, otherwise false.

Python callable() Function Example

x = 8  
print(callable(x))

Output:

False

Python compile() Function

The python compile() function takes source code as input and returns a code object which can later be executed by exec() function.

Python compile() Function Example

# compile string source to code  
code_str = 'x=5\ny=10\nprint("sum =",x+y)'  
code = compile(code_str, 'sum.py', 'exec')  
print(type(code))  
exec(code)  
exec(x)  

Output:

<class 'code'>
sum = 15

Python exec() Function

The python exec() function is used for the dynamic execution of Python program which can either be a string or object code and it accepts large blocks of code, unlike the eval() function which only accepts a single expression.

Python exec() Function Example

x = 8  
exec('print(x==8)')  
exec('print(x+4)')  

Output:

True
12