Function Details: compile

Description


Compiles the source into a code or AST object.


Extended Description


The compile() function compiles the source into a code object or AST object. It can be used to compile Python source code that can be executed later using eval() or exec(). This function is particularly useful when you need to execute code multiple times, as compilation is done only once.


Exceptions


  • SyntaxError: If the source code is syntactically incorrect
  • ValueError: If an invalid argument is passed
  • TypeError: If the arguments have inappropriate types

Read More about compile from Python Documentation

Function Signature


compile(source: Union[str, bytes, AST], filename: str, mode: str, flags: int = 0, dont_inherit: bool = False, optimize: int = -1) -> code

Module: builtins

Parameters


source: The source code to compile. Can be a string, bytes object, or an AST object. filename: The filename from which the code was read. If it wasn't read from a file, you can use '<string>'. mode: Specifies what kind of code is being compiled; 'exec' for a module, 'eval' for expressions, or 'single' for a single interactive statement. flags and dont_inherit: Control which future statements affect the compilation of source. optimize: Optimization level of the compiler; -1 means default optimization level.


Parameter List


  • source: Union[str, bytes, AST]
  • filename: str
  • mode: str
  • flags: int
  • dont_inherit: bool
  • optimize: int

Return


Returns a code object that can be executed by eval() or exec(), or an AST object that can be compiled and executed.


Return Type


code

Output

Explanation

This example compiles a simple expression and evaluates it using eval().