Python: compile() function

compile() function

The compile() function is used to compile the source into a code.

The function raises SyntaxError if the compiled source is invalid, and TypeError if the source contains null bytes.


compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)


(Python 3.2.5)


Name Description Required /
source A normal string, a byte string, or an AST object Required
filename The name of the file file from which the code was read. If it wasn't read from a file, you can give a name yourself Required
mode Either exec or eval or single. Required
flags Controls which future statements affect the compilation of the source. Default Value: 0 Optional
dont-inherit How to compile the source. Default False Optional
optimize Optimization level of the compiler. Default value -1. Optional

Return value:

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn't read from a file ('<string>' is commonly used).

Example: Python compile() function

codeInString = 'x = 8\ny=5\nsum=x+y\nprint("sum =",sum)'
codeObejct = compile(codeInString, 'sumstring', 'exec')


sum = 13

Python Code Editor:

Previous: classmethod()
Next: complex()

Test your Python skills with w3resource's quiz

Python: Tips of the Day

How do I check if a list is empty?

For example, if passed the following:

a = []
if not a:
  print("List is empty")

Ref: https://bit.ly/2A4JXx9