1. Inside the Python Engine: How CPython Works
When you run a Python script (python app.py), you are invoking CPython—the reference implementation of Python authored in ANSI C.
CPython does not execute line-by-line raw plaintext; it follows a high-speed two-phase pipeline:
[ Source Code File: script.py ]
|
v [ Phase 1: Compiler Frontend ]
+---------------------------------------------------------------+
| 1. Lexer & Parser: Generates Abstract Syntax Tree (AST) |
| 2. Bytecode Compiler: Generates platform-neutral opcodes |
| 3. Caches compiled bytecode into __pycache__/script.cpython.pyc|
+---------------------------------------------------------------+
|
v [ Phase 2: CPython Virtual Machine (PVM) ]
+---------------------------------------------------------------+
| Evaluation Loop: |
| - Reads 2-byte bytecode instructions (LOAD_CONST, BINARY_OP) |
| - Manipulates values on a runtime evaluation stack |
| - Calls C runtime functions to interact with OS and hardware |
+---------------------------------------------------------------+
|
v
[ Output to Screen / File / Network ]2. Static Typing (C++) vs. Dynamic Object References (Python)
Understanding the difference between C++ and Python memory models is fundamental to mastering computer science:
In C++ (Static Variable Memory Box):
int score = 100;
[ Memory Address 0x7ffd9a ] ---> [ Exactly 4 Bytes allocated for 32-bit Integer 100 ]
(You CANNOT later assign score = "One Hundred" because the type and size are locked)
In Python (Dynamic Pointer to Heap Object):
score = 100
[ Variable Name 'score' ] ---> [ Pointer ] ---> [ PyObject on Heap ]
- Type: int
- RefCount: 1
- Value: 100
score = "One Hundred"
[ Variable Name 'score' ] ---> [ Pointer ] ---> [ New PyObject on Heap ]
- Type: str
- RefCount: 1
- Value: "One Hundred"Duck Typing in Python: "If it walks like a duck and quacks like a duck, it's a duck." Python does not verify whether an object belongs to a rigid type class; it simply checks whether the object supports the requested operation at runtime.
3. Interactive Prototyping: The Python REPL
One of Python's greatest advantages over C++ is the REPL (Read-Eval-Print Loop), allowing instant experimentation:
# Launch the interactive shell in your terminal:
# $ python
>>> greeting = "Hello, Python Developer!"
>>> len(greeting)
25
>>> greeting.upper()
'HELLO, PYTHON DEVELOPER!'
>>> [x**2 for x in range(6)]
[0, 1, 4, 9, 16, 25]