7.1 How Python Code Runs
Python is a compiled-to-bytecode, interpreted-at-runtime language:
Source Code (.py) → Compiler → Bytecode (.pyc) → CPython VM → Machine Code
- Lexing & Parsing: source is tokenized and parsed into an Abstract Syntax Tree (AST).
- Compilation: AST → bytecode (cached in
__pycache__/*.pyc). - Execution: CPython’s stack-based virtual machine executes bytecode instruction by instruction.
import dis
def greet(name):
return f"Hello, {name}!"
dis.dis(greet)
# 2 0 LOAD_CONST 1 ('Hello, ')
# 2 LOAD_FAST 0 (name)
# 4 FORMAT_VALUE 0
# 6 LOAD_CONST 2 ('!')
# 8 BUILD_STRING 3
# 10 RETURN_VALUE
| Implementation | Description | Use Case |
|---|---|---|
| CPython | Reference implementation in C | Default, most libraries |
| PyPy | JIT-compiled Python | Performance-critical apps (4-10x faster) |
| Jython | Python on JVM | Java integration |
| IronPython | Python on .NET CLR | .NET integration |
| GraalPy | Python on GraalVM | Polyglot applications |
7.2 Everything Is an Object
Variables are names bound to objects, not storage locations.
a = 42
b = a # 'b' references the SAME object as 'a'
print(a is b) # True — id(a) == id(b)
a = 100 # Rebinds 'a' to a new object; 'b' is untouched
print(b) # Still 42
| Operator | What It Checks |
|---|---|
== |
Value equality (calls __eq__) |
is |
Identity (same object in memory) |
id() |
Memory address of object |
CPython interns small integers (-5 to 256) and simple string literals, which is why is comparisons on them can misleadingly appear to “work” — never use is for value comparison; reserve it for None/singleton checks.
7.3 Duck Typing and Dynamic Typing
class Duck:
def quack(self): return "Quack!"
class Person:
def quack(self): return "I can quack too!"
def make_it_quack(thing):
return thing.quack() # Don't check isinstance — just call the method
make_it_quack(Duck()) # "Quack!"
make_it_quack(Person()) # "I can quack too!"
7.4 The Data Model — Dunder Methods
class Money:
def __init__(self, amount: float, currency: str = "USD"):
self.amount = amount
self.currency = currency
def __repr__(self) -> str:
"""Unambiguous, for developers. eval(repr(obj)) should recreate obj."""
return f"Money({self.amount!r}, {self.currency!r})"
def __str__(self) -> str:
"""Human-readable, for end users. Falls back to __repr__ if absent."""
return f"${self.amount:.2f} {self.currency}"
def __eq__(self, other) -> bool:
if not isinstance(other, Money):
return NotImplemented
return self.amount == other.amount and self.currency == other.currency
def __hash__(self) -> int:
"""Required for set/dict-key usage. Must be consistent with __eq__."""
return hash((self.amount, self.currency))
def __add__(self, other) -> "Money":
if not isinstance(other, Money):
return NotImplemented
if self.currency != other.currency:
raise ValueError(f"Cannot add {self.currency} and {other.currency}")
return Money(self.amount + other.amount, self.currency)
def __bool__(self) -> bool:
return self.amount != 0
m1, m2 = Money(100, "USD"), Money(50, "USD")
print(m1 + m2) # $150.00 USD
prices = {m1, m2} # Works because __hash__ and __eq__ are defined
Python Data Model summary:
Lifecycle: __init__, __new__, __del__, __repr__, __str__
Comparison: __eq__, __lt__, __le__, __gt__, __ge__
Arithmetic: __add__, __sub__, __mul__, __truediv__ (+ __r*__, __i*__ variants)
Container: __len__, __getitem__, __setitem__, __delitem__, __contains__, __iter__
Attribute: __getattr__, __setattr__, __getattribute__
Callable: __call__
Context Manager: __enter__, __exit__
Hashing: __hash__
Descriptor: __get__, __set__, __delete__
Interview Q&A — Section 7
Q1: Is Python compiled or interpreted?
A: Python source is compiled to bytecode (cached in
.pycfiles), which is then interpreted by the CPython virtual machine — a “compiled-to-bytecode, interpreted-at-runtime” language, distinct from both fully-compiled languages and pure line-by-line interpreters.
Q2: What happens when you run a = b = [1, 2, 3] then a.append(4)? What is b?
A:
bis[1, 2, 3, 4]. The statement creates one list object and binds both names to it (a is bisTrue).appendmutates that shared object in place, so both names observe the change. To avoid this, copy explicitly:b = a.copy().
Q3: What is the difference between __repr__ and __str__, and which is more important?
A:
__repr__is the unambiguous, developer-facing representation (ideallyeval(repr(obj))recreates the object) and is what containers, the interactive shell, and debuggers use.__str__is the readable, end-user-facing representation used byprint()/str().__repr__is more important — it’s the fallback used whenever__str__isn’t defined, and it’s essential for debugging, so always implement it.
Q4: Explain Python’s garbage collection and how it differs from Java’s.
A: Python uses reference counting as its primary mechanism — every object tracks how many references point to it, and it’s freed immediately when the count hits zero, giving deterministic cleanup. A secondary generational garbage collector (three generations, gc module) handles reference cycles that counting alone can’t detect. Java’s JVM instead uses a purely tracing garbage collector (mark-sweep-compact across generational or region-based heaps) with no reference counting, so cleanup timing is non-deterministic but cycles are handled naturally as part of the same mechanism.