Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Python FAQ: Top Questions

3. Is Python a compiled or interpreted language?

This is a common question with a nuanced answer: Python is generally considered an **interpreted language**, but it involves a compilation step that is largely hidden from the user. Understanding this distinction is crucial to grasp how Python executes code.

  • The Role of the Interpreter:
    • When you run a Python script (a `.py` file), the **Python interpreter** reads and executes the code line by line. This is the characteristic of an interpreted language, contrasting with compiled languages like C++ or Java, where source code is explicitly translated into a machine-readable executable file before execution.
    • This immediate execution makes Python excellent for rapid prototyping, scripting, and interactive use (e.g., in a Python shell).
  • Hidden Compilation to Bytecode:
    • Before execution, the Python interpreter performs an internal compilation step. It translates the human-readable Python source code into a lower-level, platform-independent intermediate format called **bytecode**.
    • This bytecode is a set of instructions that the **Python Virtual Machine (PVM)** can understand and execute.
    • If the module is imported or run as a script, this bytecode is typically cached in files with a `.pyc` extension (e.g., `my_script.cpython-3x.pyc`) within a `__pycache__` directory.
  • Execution by the PVM:
    • The PVM is the runtime engine that interprets and executes the bytecode. It's essentially a software implementation of a CPU.
    • This two-step process (source code -> bytecode -> PVM execution) provides several benefits:
      • Faster Startup: If the bytecode (`.pyc` file) already exists and is up-to-date, the interpreter can skip the source-to-bytecode compilation step, leading to faster program startup on subsequent runs.
      • Portability: The bytecode is platform-independent. This allows `.pyc` files to be moved and executed on any system that has a compatible Python interpreter and PVM installed, contributing to Python's "write once, run anywhere" capability.

So, while Python *does* compile code, this compilation is usually implicit and happens automatically as part of the interpretation process, making it primarily classified as an interpreted language from a user's perspective.


# --- Example: A simple Python script (my_script.py) ---
# When you run this file, Python will first compile it into bytecode,
# then execute that bytecode using the Python Virtual Machine (PVM).

def add(a, b):
    """
    A simple function to add two numbers.
    """
    print(f"Executing add({a}, {b})...")
    return a + b

# Call the function
result = add(2, 3)
print(f"Result of addition: {result}")

# Demonstrate how Python handles code after definition
message = "Script finished."
print(message)

# To observe the .pyc file:
# 1. Save the above code as 'my_script.py'.
# 2. Open your terminal or command prompt.
# 3. Navigate to the directory where you saved 'my_script.py'.
# 4. Run the script: 'python my_script.py'
# 5. After the first run, you should find a new directory named '__pycache__'
#    in the same location as 'my_script.py'.
# 6. Inside '__pycache__', you'll see a file like 'my_script.cpython-3xx.pyc'
#    (where '3xx' corresponds to your Python version, e.g., 3.9, 3.10).
#    This is the compiled bytecode file.
          

Explanation of the Example Code:

  • The provided code snippet for `my_script.py` is a standard Python source file.
  • When you execute `python my_script.py` for the first time, the Python interpreter will:
    1. Read the `my_script.py` source code.
    2. Parse it and convert it into **bytecode**.
    3. Execute this bytecode using the PVM, producing the output (`Executing add(2, 3)...`, `Result of addition: 5`, `Script finished.`).
    4. As a side effect (if the script is a module being imported, or for main scripts when it's beneficial), it will typically save this generated bytecode into a `.pyc` file inside a `__pycache__` directory. This cached bytecode speeds up subsequent executions of the script because the interpreter can load the `.pyc` directly, skipping the initial parsing and compilation step.
  • The instructions at the end of the example guide you to manually observe the creation of the `__pycache__` directory and the `.pyc` file, visually confirming the hidden compilation process that Python performs.

This demonstrates that while we directly run the `.py` file, Python's underlying mechanism involves an intermediate compilation step to bytecode, which is then interpreted by the PVM.