Executing Python Code: A Comprehensive Guide to Source Code Execution

28 Nov 2023 Balmiki Mandal 0 Python

Exploring the Internal Mechanisms of Python Programming

Python is an interpreted language, which means it does not need to be compiled into machine code before it can be executed. However, Python does go through a compilation stage where it is converted into bytecode. Bytecode is a form of code that is more efficient for the Python interpreter to execute than the original Python source code.

Diagram of the Internal working of Python (compilation stages)

 

Source code --> Tokenization --> Parsing --> Abstract Syntax Tree --> Bytecode --> Execution

 

Tokenization:

In the first stage, the Python compiler breaks the source code into tokens. Tokens are the basic building blocks of Python code, such as keywords, identifiers, operators, and punctuation.

Parsing:

In the second stage, the Python compiler parses the tokens to check that the code is syntactically correct. This means that the compiler checks that the code follows the rules of the Python language.

Abstract Syntax Tree (AST):

If the code is syntactically correct, the compiler creates an AST. An AST is a tree-like data structure that represents the structure of the code.

Bytecode:

The compiler then converts the AST into bytecode. Bytecode is a form of code that is more efficient for the Python interpreter to execute than the original Python source code. Bytecode is stored in .pyc files.

Execution:

Finally, the Python interpreter executes the bytecode. The interpreter reads the bytecode and executes the corresponding Python instructions.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.