compile()

christian.dinh2481 total contributions
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.
All contributors
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor194 total contributions
- Anonymous contributorAnonymous contributor2 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- christian.dinh
- Anonymous contributor
- Anonymous contributor
- Anonymous contributor
Looking to contribute?
- 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.