Python compile()
Anonymous contributor
Published Jul 6, 2021Updated Aug 7, 2023
Contribute to Docs
Returns a runnable code object created from a string.
Syntax
compile(source, filename, mode)
Parameters
source: string or AST objectfilename: The file from which the code is being readmode:eval: It accepts only a single expression.exec: It can take a code block that has Python statements, class and functions, and so on.single: It consists of a single interactive statement.
flags(optional) anddont_inherit(optional): Controls which future statements affect the compilation of the source. Default set to 0.optimize(optional): The optimization level of the compiler. Default set to -1.
Example
Use compile() to take a code block containing a function and a statement, to return a runnable code object.
def dog():print("Woof woof wooo!")friend = compile('print("Who\'s a good boy?")\ndog()', 'test', 'exec')exec(friend)
This will output:
Who's a good boy?Woof woof wooo!
Codebyte Example
Use compile() to take a code block containing a single expression and return a runnable code object.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours