Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What is compile() in Python?

Rameen Farrukh

The compile() method takes in an input code and returns a code object that can easily be executed.

Syntax

compile(*source, filename, mode, flags=0, dont_inherit=False, optimize=-1*)

Parameters

  • source: The source can be an AST object or a normal/byte string.

  • filename: The file from where we read the code.

  • mode: There are three types of mode. For a single expression source, the mode is eval. If the code consists of a single interactive statement, the mode is single. The exec mode takes a block of a code that has statements, classes, and functions.

  • flags (optional): The default for this is 0.

  • dont_inherit (optional): The default for this is 0.

  • optimize (optional): The optimization level of the compiler can be specified by this. Its default value is -1.

Use

If the Python code you have is in the form of a string or an AST object and you need to change it to a code object, use compile().

Code

number = 30 
x = compile('number', 'test', 'single')
eval(x)

In order to execute the result returned by compile(), there are two inbuilt functions that can be used:

  1. exec()
  2. eval()

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring