VOOZH about

URL: https://www.codecademy.com/resources/docs/python/built-in-functions/compile

⇱ Python | Built-in Functions | compile() | Codecademy


Skip to Content

Python compile()

Preview: Anonymous contributor 189 total contributions
Anonymous contributor

189 total contributions

Published Jul 6, 2021Updated Aug 7, 2023

Returns a runnable code object created from a string.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 CoursesIncludes 6 Courses
    • With Professional CertificationWith Professional Certification
    • Beginner Friendly.
      75 hours75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With CertificateWith Certificate
    • Beginner Friendly.
      24 hours24 hours

Syntax

compile(source, filename, mode)

Parameters

  • source: string or AST object
  • filename: The file from which the code is being read
  • mode:
    • 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) and dont_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.

defdog():
print("Woof woof wooo!")
friend =compile('print("Who\'s a good boy?")\ndog()','test','exec')
exec(friend)
Copy to clipboard
Copy to clipboard

This will output:

Who's a good boy?
Woof woof wooo!
Copy to clipboard
Copy to clipboard

Codebyte Example

Use compile() to take a code block containing a single expression and return a runnable code object.

Visit us
Visit us
Hide code
Code
Output
Hide output
Copy to your clipboard

All contributors

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 CoursesIncludes 6 Courses
    • With Professional CertificationWith Professional Certification
    • Beginner Friendly.
      75 hours75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With CertificateWith Certificate
    • Beginner Friendly.
      24 hours24 hours