compile() Compile source to code object

Last updated: 2026-09-22

compile() Compile source to code object

compile() compiles source string into a code object that can be executed by exec() / eval().

CategoryBuilt-in Functions
KindBuilt-in Function
Python Versionall

📝 Syntax

compile(source, filename, mode)

⚙️ Parameters

source RequiredSource code: a string, bytes, or AST object.
filename RequiredFilename shown in error messages; pass '' for inline source.
mode RequiredCompilation mode: 'exec', 'eval', or 'single'.
flags OptionalCompiler flags, e.g. ast.PyCF_ONLY_AST.(Default:0)
dont_inherit OptionalWhether to ignore surrounding compile flags.(Default:False)
optimize OptionalOptimization level; -1 uses the interpreter's setting.(Default:-1)

Returns:A code object executable by exec() / eval().

💥 Raises

▶ Example

Edit the code, press Run, and see the result in the output panel:

Output:

3
More case studies coming soon — check back later.

❓ FAQ

QWhat is the difference between the three modes of compile()?
A'exec' compiles a statement block (if, def, for, etc.), 'eval' compiles a single expression (which can be evaluated to a value), and 'single' compiles a single interactive statement and will print expression results.
QWhat should I pass for the filename argument?
AFor dynamically generated inline code, the convention is to pass ''. It only appears in error messages (the traceback) and has nothing to do with a real file — it never actually reads one.
QAfter compile(), how do I execute the result?
APass the returned code object to exec(code) or eval(code): code compiled in 'exec' mode is run with exec, 'eval' mode with eval.
QWhat happens if the source has a syntax error?
AA SyntaxError is raised at the compile() stage — earlier than executing the string directly, which is ideal for 'compile first, execute later' scenarios.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏