🐍
Python
⚙️ Inner Working of Python
1️⃣ Python Execution Flow
When you run a Python program:
python [Link]
This happens step by step:
1. Source Code ( .py ) → You write human-readable Python code.
2. Bytecode Compilation → Python internally compiles it into bytecode ( .pyc
files).
Stored in __pycache__ folder.
Faster execution next time.
Works only for imported files.
Not for top level files.
3. Python Virtual Machine (PVM) (Runtime Engine) → Bytecode is executed
by the Python interpreter (CPython).
Python 1
4. C Libraries / OS → If needed, Python calls underlying C code and OS-level
functions.
👉 Example: print("Hello") → Python converts to bytecode → PVM → calls C printf()
function under the hood.
2️⃣ Python Interpreter (CPython)
The default Python implementation is CPython, written in C.
It includes:
Parser → Reads & checks syntax.
Compiler → Converts to bytecode.
PVM (Python Virtual Machine) → Executes instructions line by line.
👉 Other implementations:
Jython → Python on JVM.
IronPython → Python on .NET CLR.
PyPy → Python with JIT (much faster).
3️⃣ Memory Management in Python
Python manages memory automatically using Garbage Collection (GC).
Objects are stored in heap memory.
Every object has a reference count.
👉 Example:
a = [1,2,3]
b = a # reference count increases
del a # reference count decreases
When reference count = 0 → Python frees memory.
GC also uses cyclic garbage collector for complex cases (like objects
referring to each other).
Python 2
4️⃣ Python is Interpreted but also Compiled
People say Python is interpreted, but actually:
It is compiled to bytecode first (hidden from you).
Then interpreted by PVM.
This makes Python slower than C/C++ but more flexible & portable.
5️⃣ Global Interpreter Lock (GIL)
In CPython, only one thread executes at a time due to GIL.
Useful for memory safety, but slows down multi-threading.
Solution: Use multiprocessing for parallelism (separate processes).
6️⃣ Example: Inner Flow of Code
x=5
y = 10
print(x + y)
Step by step:
1. Parser → checks syntax ( x=5 , y=10 ).
2. Compiler → converts into bytecode instructions.
3. PVM executes:
Create object 5 in memory, bind to x .
Create object 10 , bind to y .
Perform addition via C functions.
Print result to screen.
🔑 Key Takeaways
Python runs in two steps: Compile → Interpret.
Uses bytecode + PVM.
Python 3