How Python Works: From Code to Execution – A Deep Dive

Python is one of the most popular and beginner-friendly programming languages in the world. It's used in web development, data science, automation, machine learning, and more. But to truly harness its power, you need to understand How Python Works: From Code to Execution – A Deep Dive

This guide explains Python's architecture, interpreter, execution flow, memory management, and more, with simplified diagrams and sketches to help visualize the process.

1. Introduction to Python

Python is a high-level, interpreted, and object-oriented language. Unlike C or Java, where the code must be compiled, Python runs your code line by line using an interpreter.

Key Features:

  • Interpreted: No compilation step is needed.

  • Dynamic typing: You don’t need to declare variable types.

  • Automatic memory management: Handled by Python’s garbage collector.

  • Extensible: Python can integrate with C/C++ code for performance.

2. Python Execution Flow

When you write a Python script and run it, a series of steps takes place to convert your code into actions the computer can understand.

Step-by-Step Python Execution Process

Source Code (.py)
     ↓
Python Interpreter
     ↓
Bytecode (.pyc)
     ↓
Python Virtual Machine (PVM)
     ↓
Execution Output

πŸ”§ 1. Writing Python Code

# example.py
a = 5
b = 10
print(a + b)

This code is human-readable and saved with an .py extension.

πŸ”§ 2. Python Interpreter Converts Code to Bytecode

The Python interpreter (like CPython, the most commonly used version) first parses and compiles the source code into bytecode, an intermediate format.

Bytecode is a low-level, platform-independent representation of your code.

Sketch: Bytecode Compilation

def add():
    a = 5
    b = 10
    return a + b

↓  (Compilation Step)

[ LOAD_CONST 5, LOAD_CONST 10, BINARY_ADD, RETURN_VALUE ]

These bytecode instructions are stored in .pyc files under the __pycache__ folder.

πŸ”§ 3. Execution via Python Virtual Machine (PVM)

The PVM reads bytecode line by line and executes it. It’s like a runtime engine that interprets and executes Python bytecode.

The PVM handles execution, memory allocation, and garbage collection.

πŸš€ Supercharge Your Project Management with ByteScrum!

Struggling to keep your projects on track? ByteScrum is the ultimate agile project management tool designed to help teams collaborate efficiently and deliver results faster!

βœ… Streamline workflows with powerful Scrum & Kanban boards
βœ… Bo
ost team productivity with real-time collaboration
βœ… Track progress effortlessly with intuitive dashboards
βœ… Stay organized with task management & automation

πŸš€ Ready to take your projects to the next level?
Try ByteScrum today and experience seamless project management like never before! πŸ”₯

3. Components of the Python Execution Environment

βœ… 1. Python Compiler

Compiles .py to .pyc files.

βœ… 2. Interpreter / PVM

Executes bytecode line-by-line.

βœ… 3. Memory Manager

Handles object allocation, garbage collection, and memory reuse.

βœ… 4. Built-in Data Types and Libraries

Python provides rich built-in types like int, list, dict, and many standard modules (math, random, etc.).

4. Types of Python Interpreters

There are several implementations of the Python interpreter:

InterpreterLanguageKey Feature
CPythonCOfficial version, most widely used
JythonJavaPython on the Java platform
PyPyPythonFaster execution using JIT compiler
IronPythonC#Integrates with .NET framework

5. Memory Management in Python

Python uses automatic memory management via a built-in Garbage Collector (GC).

+-------------------------+     +--------------------------+
|        Stack            |     |          Heap            |
|                         |     |                          |
| - Function frames       |     | - Objects (lists, dicts) |
| - Local variables       |     | - Class instances        |
+-------------------------+     +--------------------------+

πŸ” Python Memory Workflow:

Code Variables β†’ Memory Allocation β†’ Reference Counting β†’ Garbage Collection

πŸ”Ή Reference Counting

Every object in Python has a reference count. When no variables reference the object, it is garbage collected.

a = [1, 2, 3]  # reference count = 1
b = a          # reference count = 2
del a          # reference count = 1
del b          # reference count = 0 β†’ object deleted

πŸ”Ή Garbage Collection

Python also uses a cyclic garbage collector to find objects that reference each other and are no longer needed.

6. Python Stack and Heap

Memory in Python is divided into two main areas:

Memory TypePurpose
StackStores function calls and local variables
HeapStores objects like lists, dictionaries, custom classes

Sketch of Python Memory Layout:

+-----------------+
| Python Stack    | <---- Function calls, local vars
+-----------------+
| Python Heap     | <---- Objects, classes, lists, etc.
+-----------------+

Each time you call a function, a new frame is pushed onto the stack.

7. Python Object Model

Everything in Python is an object, including numbers, functions, and even modules.

type(5)            # <class 'int'>
type(len)          # <class 'builtin_function_or_method'>
type("hello")      # <class 'str'>

Object Internals

Each object has:

  • Type: Defined at creation

  • ID: Unique memory address

  • Reference Count: Number of references to it

8. Python Code Execution in Action

Let’s walk through an example:

def greet(name):
    return "Hello, " + name

greet("Alice")

Step-by-Step:

  1. Python parses and compiles the code to bytecode.

  2. A function object greet is created.

  3. greet("Alice") is called.

  4. The stack frame is created.

  5. "Hello, " + name is executed.

  6. Result returned, stack frame popped.

9. Python Bytecode Explained

You can use the dis Module to inspect bytecode:

import dis

def add():
    return 1 + 2

dis.dis(add)

Output:

 2           0 LOAD_CONST               1 (1)
              2 LOAD_CONST               2 (2)
              4 BINARY_ADD
              6 RETURN_VALUE

This is what the PVM reads and executes.

10. Just-In-Time Compilation with PyPy

While CPython is interpreted, PyPy uses Just-In-Time (JIT) compilation to speed up execution.

  • JIT compiles hot code paths into machine code.

  • Great for long-running applications (e.g., web servers, scientific computation).

11. Multithreading and GIL (Global Interpreter Lock)

Python’s CPython interpreter has a Global Interpreter Lock (GIL), which prevents multiple threads from executing Python bytecode simultaneously.

Implication:

  • Good for I/O-bound tasks.

  • Poor for CPU-bound tasks in pure Python.

You can use:

  • multiprocessing for CPU-bound parallelism.

  • asyncio for asynchronous I/O.

12. Python Internals Overview Diagram

         +-------------------------+
          |     Python Code (.py)  |
          +-------------------------+
                      ↓
            Python Compiler β†’ Bytecode (.pyc)
                      ↓
        +---------------------------+
        | Python Virtual Machine    |
        |  (Executes Bytecode)      |
        +---------------------------+
         ↓          ↓             ↓
  Memory Mgmt   Function Stack   Output

13. Tools to Explore Python Internals

If you want to explore Python deeper, try these tools:

ToolPurpose
disDisassembles bytecode
gcAccess the garbage collector
pdbPython debugger
objgraphVisualize memory and object references
tracemallocTrack memory usage

14. Real-World Use Case: Script Execution

# email_sender.py

def send_email(to, subject):
    print(f"Sending email to {to} with subject: {subject}")

send_email("user@example.com", "Welcome!")

Execution Flow:

  1. Python interpreter starts.

  2. The compiler parses and converts the code into bytecode.

  3. PVM executes each bytecode instruction.

  4. Memory allocated for strings, functions, etc.

  5. Stack frames are managed for function calls.

  6. The output is printed.

βœ… Recap

  • Python is interpreted, not compiled.

  • It compiles code to bytecode and runs it using a Virtual Machine.

  • Memory management is automatic with reference counting and garbage collection.

  • Python's performance is limited by the GIL but can be enhanced with multiprocessing or tools like PyPy.

  • Everything in Python is an object, including functions and numbers.

πŸ“Œ Conclusion

Understanding how Python works internally gives you a deeper insight into writing better, more optimized code. Whether you're debugging a tricky issue or optimizing for performance, knowing the role of the interpreter, bytecode, memory model, and execution flow is crucial.

If you're building projects, testing performance, or simply learning Python more deeply, revisit this internal architecture often. It’s the foundation of the language.

πŸš€ Boost Your Productivity with UtilsHub!

Looking for a fast, free, and reliable way to handle everyday online tasks? UtilsHub is your ultimate all-in-one utility platform!

βœ… Convert, edit, and optimize files effortlessly βœ… Access a wide range of tools – from text manipulation to image editing
βœ… Completely free & easy to use – No downloads or sign-ups required!

πŸ”— Try it now! Click here πŸ‘‰ UtilsHub and simplify your workflow today! πŸš€

10
Subscribe to my newsletter

Read articles from ByteScrum Technologies directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ByteScrum Technologies
ByteScrum Technologies

Our company comprises seasoned professionals, each an expert in their field. Customer satisfaction is our top priority, exceeding clients' needs. We ensure competitive pricing and quality in web and mobile development without compromise.