Notes
All notes

Python: from names to concurrency

Python’s reputation as a readable first language hides how much theory sits underneath it. Why does a = [1] and b = a make two names for one list? Why is 0.1 + 0.2 not 0.3? Why does adding threads not speed up a CPU-bound loop, but adding them does speed up a network call? Every one of those surprises comes from the object model, the numeric model, and the concurrency model — and knowing them is the difference between code that works and code that is correct.

This post follows the roadmap.sh/python path in one guide. It is deliberately theory-first: names and references, mutability, scope, the iterator protocol, the GIL, and the async event loop explain why the idioms work. Code is interleaved throughout, and self-test question blocks follow the relevant sections.

The execution model

Python is an interpreted, dynamically typed, garbage-collected, high-level language. “Interpreted” is a shorthand: CPython (the reference implementation) first compiles your source to an intermediate bytecode, then executes that bytecode on a virtual machine. That is why syntax errors are reported before runtime, why importing a module writes a .pyc cache, and why CPython is slower than a compiled language for tight numeric loops.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=2.2cm, minimum height=0.68cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (src) at (0,0) {source .py};
  \node[b, fill=orange!16] (bc) at (3.2,0) {bytecode .pyc};
  \node[b, fill=green!14] (pvm) at (6.4,0) {CPython VM};
  \draw[a] (src) -- node[above, font=\scriptsize] {compile} (bc);
  \draw[a] (bc) -- node[above, font=\scriptsize] {execute} (pvm);
\end{tikzpicture}

Two type-system facts matter. Dynamic typing means a name has no type; the object it refers to does, and that is checked at runtime. Strong typing means values do not silently coerce: "1" + 1 raises TypeError, it does not produce "11" or 2. This is the “batteries included” language you were told was easy — easy to read, strict underneath.

QQuestionIs Python interpreted or compiled?
ASolution

Both, in a sense. CPython compiles source to intermediate bytecode (__pycache__/*.pyc) and then executes that bytecode on a virtual machine. It is “interpreted” in that there is no ahead-of-time machine-code step you control, but it is not reading your source line by line at runtime.

QQuestionIs Python statically or dynamically typed? Weakly or strongly typed?
ASolution

Dynamically typed: types are checked at runtime and a name can refer to objects of different types over time. But strongly typed: values do not silently coerce, so "1" + 1 raises TypeError instead of producing "11" or 2.

Names, objects, and the data model

Every value in Python is an object with three things: an identity (id), a type (type), and a value. A variable is a name bound to an object — a reference, not a box holding the value. Assignment rebinds the name; it does not copy.

a = [1, 2, 3]
b = a              # b refers to the SAME list
b.append(4)
print(a)           # [1, 2, 3, 4] -- both names see the change
print(a is b)      # True: same object
print(a == b)      # True: same value
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={font=\small\ttfamily},
  o/.style={draw, thick, rounded corners=3pt, minimum width=2.0cm, minimum height=0.7cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[n] (x) at (0,0.8) {a};
  \node[n] (y) at (0,-0.2) {b};
  \node[o, fill=green!14] (obj) at (3,0.3) {[1, 2, 3, 4]};
  \draw[a] (x) -- (obj);
  \draw[a] (y) -- (obj);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (1.5,-0.9) {two names, one object};
\end{tikzpicture}

Identity vs equality. is compares identity (the same object); == compares value (via __eq__). Use is only for None, True, False, and sentinels — never for numbers or strings. x is None is idiomatic; x == None works but is discouraged. Implementation detail: CPython interns small integers and some strings, so is sometimes appears to work for them — do not rely on it.

Mutability is per-type and decides what operations can do:

Immutable (cannot change) Mutable (can change)
int, float, bool, str, bytes, tuple, frozenset, None list, dict, set, bytearray, most user objects

Immutability is what makes an object hashable (its hash must not change), which is why dictionary keys and set elements must be immutable. A tuple of immutables is hashable; a tuple containing a list is not.

Copying has two depths. copy.copy is a shallow copy: a new outer object, but nested objects are shared. copy.deepcopy recursively copies nested objects. The default for b = a is neither — it copies nothing.

import copy
a = [[1, 2], [3, 4]]
shallow = copy.copy(a)      # new outer list, SAME inner lists
deep = copy.deepcopy(a)     # everything independent
shallow[0].append(99)       # mutates a[0] too!
print(a)                    # [[1, 2, 99], [3, 4]]
print(deep)                 # [[1, 2], [3, 4]]
QQuestionWhat is the difference between is and ==?
ASolution

is compares identity (whether two names refer to the same object); == compares value (via __eq__). Use is only for None, True, False, and sentinels. CPython may intern small ints and some strings, so is can appear to work for them, but relying on that is a bug.

QQuestionWhat is the difference between a shallow copy and a deep copy?
ASolution

A shallow copy (copy.copy) creates a new outer object but shares the nested objects, so mutating a nested list is visible in both. A deep copy (copy.deepcopy) recursively copies everything, so the two are fully independent. Plain assignment (b = a) copies nothing at all.

QQuestionWhat are mutable and immutable types, and why does it matter?
ASolution

Immutable objects cannot change after creation (int, float, str, tuple, frozenset, None); mutable ones can (list, dict, set). It matters because only immutable objects (with a stable hash) can be dictionary keys or set elements, and because mutable objects shared between names can be mutated unexpectedly.

Variables, data types, and operators

Numbers. int is arbitrary precision (no overflow). float is IEEE-754 binary64, so most decimals are approximate — never compare floats with ==, and never store money as a float. Use Decimal for exact decimal arithmetic and Fraction for rationals.

print(0.1 + 0.2)            # 0.30000000000000004
print(round(0.1 + 0.2, 2))  # 0.3
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))   # 0.3 exactly

Text and bytes. str is a sequence of Unicode code points; bytes is a sequence of bytes. Encoding converts str to bytes (text.encode("utf-8")), decoding converts back. Mixing them raises TypeError — a deliberate design choice that prevents mojibake.

Booleans and truthiness. bool is a subclass of int (True == 1). Every object has a truth value: empty containers, 0, "", and None are falsy; almost everything else is truthy. Write if items: rather than if len(items) > 0:.

Operators. Arithmetic (+ - * / // % **), comparison chaining (0 <= x < 10), logical and/or/not with short-circuit evaluation, bitwise (& | ^ ~ << >>), membership (in), identity (is), and the walrus := for assignment expressions inside conditions.

if (n := len(data)) > 10:
    print(f"large: {n}")

and and or return one of their operands, not a bool, which enables the x or default idiom — and also the classic bug where a valid falsy value (0, "") is replaced by the default.

QQuestionWhy is 0.1 + 0.2 not equal to 0.3?
ASolution

Python float is IEEE-754 binary64, which cannot represent most decimal fractions exactly, so the stored values are slightly off and the sum is 0.30000000000000004. Compare with a tolerance (math.isclose) or use decimal.Decimal for exact decimal arithmetic, and never store money as a float.

QQuestionWhat values are falsy in Python?
ASolution

None, False, numeric zero (0, 0.0, 0j), and empty containers/strings ("", [], {}, set(), ()). Everything else is truthy, which is why if items: is preferred over if len(items) > 0:.

Control flow

if/elif/else branches; for iterates over any iterable; while loops on a condition. range produces numbers lazily. break exits a loop, continue skips to the next iteration, and pass does nothing.

for i, name in enumerate(["ann", "bob"], start=1):
    if name == "bob":
        continue
    print(i, name)

for x, y in zip([1, 2, 3], "abc"):
    print(x, y)

Python’s for/else runs the else clause only if the loop completed without break — a clean way to express “not found”:

for n in numbers:
    if n == target:
        print("found")
        break
else:
    print("not found")

Python 3.10 added structural pattern matching (match/case), which destructures data and is far more than a switch statement.

match command.split():
    case ["go", direction]:
        move(direction)
    case ["quit"]:
        raise SystemExit
    case _:
        print("unknown")
QQuestionWhat does the else clause on a for or while loop do?
ASolution

It runs only if the loop finished without hitting break. It is the idiomatic way to express “did not find it”: loop over candidates, break on a match, and put the not-found handling in else.

QQuestionWhat is the walrus operator :=?
ASolution

An assignment expression (Python 3.8+) that assigns a value while using it in an expression, so you can both test and keep the result: if (n := len(data)) > 10:. It avoids computing a value twice.

Functions

A function is a first-class object: defined with def, it can be stored, passed, and returned. Parameters come in several kinds, and their order in the signature matters.

def f(a, b=2, *args, c, d=4, **kwargs):
    return a, b, args, c, d, kwargs

f(1, 3, 5, 6, c=7, extra=8)
# a=1, b=3, args=(5, 6), c=7, d=4, kwargs={'extra': 8}

The mutable default gotcha. Default values are evaluated once, when the function is defined — so a mutable default is shared across calls:

def bad(x, acc=[]):     # acc is created ONCE
    acc.append(x)
    return acc
print(bad(1), bad(2))   # [1] [1, 2]  -- surprising shared state!
def good(x, acc=None):
    acc = [] if acc is None else acc
    return acc

Scope follows the LEGB rule: a name resolves in the Local, then Enclosing, then Global, then Built-in scope. Assignment inside a function creates a local unless you declare global or nonlocal.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.8cm, minimum height=0.6cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=green!16] (l) at (0,0) {Local};
  \node[b, fill=blue!10] (e) at (0,-0.9) {Enclosing};
  \node[b, fill=orange!16] (g) at (0,-1.8) {Global};
  \node[b, fill=gray!12] (b2) at (0,-2.7) {Built-in};
  \draw[a] (l) -- (e); \draw[a] (e) -- (g); \draw[a] (g) -- (b2);
  \node[font=\rmfamily\small, text=black!60, anchor=west] at (1.2,-1.3) {name lookup order};
\end{tikzpicture}

Closures let an inner function capture variables from the enclosing scope, keeping them alive after the outer function returns.

def counter():
    n = 0
    def inc():
        nonlocal n          # rebind the enclosing n
        n += 1
        return n
    return inc

c = counter()
print(c(), c(), c())        # 1 2 3

Recursion is supported but Python does not optimize tail calls, so deep recursion can hit the recursion limit — prefer iteration for deep structures.

QQuestionWhat is the mutable default argument pitfall?
ASolution

Default values are evaluated once, at function definition time, so a mutable default such as def f(x, acc=[]): shares one list across every call. Use None as the sentinel and create the container inside: def f(x, acc=None): acc = [] if acc is None else acc.

QQuestionExplain *args, **kwargs, and the LEGB scope rule.
ASolution

*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. Name lookup follows LEGB: Local, then Enclosing, then Global, then Built-in. Assigning inside a function makes a name local unless you declare global or nonlocal.

QQuestionWhat is a closure?
ASolution

An inner function that captures variables from its enclosing scope and keeps them alive after the outer function returns. Use nonlocal to rebind the captured variable. Closures are the mechanism behind decorators and factory functions.

Built-in data structures

Four containers cover most needs, each with a different shape and cost:

Type Ordered Mutable Duplicates Lookup by
list yes yes yes index
tuple yes no yes index
set no yes no value
dict yes (insertion) yes keys no key
nums = [3, 1, 2]                 # list
point = (1, 2)                   # tuple
unique = {1, 2, 3}               # set
ages = {"ann": 30, "bob": 25}    # dict

Complexity is the reason to choose one over another:

Operation list dict / set
Index / key access \(O(1)\) \(O(1)\) average
Search by value \(O(n)\) \(O(1)\) average
Insert/delete at end \(O(1)\) amortized —
Insert/delete at front \(O(n)\) —
Membership in \(O(n)\) \(O(1)\) average

dict ordering is insertion order (guaranteed since 3.7), which makes it useful as an ordered mapping. Sets implement the usual mathematics: union |, intersection &, difference -, symmetric difference ^.

Comprehensions build containers from iterables in one expression, and are faster and clearer than an equivalent loop with append:

squares = [x * x for x in range(10) if x % 2 == 0]   # list
unique = {x % 3 for x in range(10)}                  # set
index = {w: len(w) for w in ["a", "bb", "ccc"]}      # dict

A comprehension is a small scope of its own, so its loop variable does not leak. For very large inputs, a generator expression (x * x for x in data) produces values lazily instead of building a list.

QQuestionWhat is the difference between a list and a tuple?
ASolution

A list is mutable, a tuple is immutable. Tuples are hashable (when their contents are), slightly lighter, and signal “this record does not change” — usable as dict keys, set elements, and function return values. Use a tuple for a fixed record and a list for a changing sequence.

QQuestionWhen would you use a set instead of a list, and what is the complexity win?
ASolution

Use a set when you need uniqueness or fast membership tests. x in list is \(O(n)\); x in set is \(O(1)\) average. Sets also give set algebra (|, &, -, ^). They are unordered and cannot contain unhashable items.

QQuestionWhat is a comprehension, and when would you prefer a generator expression?
ASolution

A comprehension builds a whole container in one expression ([x*x for x in xs]). A generator expression ((x*x for x in xs)) is lazy and produces values one at a time, using constant memory — prefer it for large or streamed inputs, or when passing straight into sum, any, max, or join.

Working with strings

Strings are immutable sequences of Unicode. Indexing, slicing, and iteration work as on lists, and slices return new strings.

s = "Hello, World"
print(s[0], s[-1])          # H d
print(s[7:12])              # World
print(s[::-1])              # dlroW ,olleH  -- reverse
print(s.upper(), s.split(", "))

Build strings with join, not repeated +, because each + creates a new string (\(O(n^2)\) overall):

parts = ["a", "b", "c"]
print(", ".join(parts))              # a, b, c

f-strings (3.6+) are the standard formatting tool and can embed expressions and format specs:

name, pi = "ann", 3.14159
print(f"{name=} {pi:.2f} {pi:>8.3f}")   # name='ann' 3.14    3.142
QQuestionAre Python strings mutable, and how do you build one efficiently?
ASolution

Strings are immutable; operations return new strings. Repeated += in a loop is \(O(n^2)\) because each step copies, so collect the pieces and call "".join(parts) once — that is linear.

QQuestionWhat is the difference between str and bytes?
ASolution

str is a sequence of Unicode code points; bytes is a sequence of raw bytes. Convert with .encode("utf-8") and .decode("utf-8"). Mixing them raises TypeError, which is deliberate: it forces you to be explicit about encoding and prevents garbled text.

Error handling

Errors are exceptions, organized in a hierarchy rooted at BaseException (with Exception as the branch you normally catch). The flow is try → except → else → finally: else runs if no exception occurred, and finally always runs, which is where cleanup belongs.

try:
    value = int(text)
except ValueError as e:
    print("not a number:", e)
except (KeyError, IndexError):
    print("missing data")
else:
    print("parsed", value)
finally:
    print("always runs")

Raise exceptions with raise, and chain to preserve the cause:

try:
    parse(config)
except KeyError as e:
    raise ConfigError("missing field") from e   # keeps the original traceback

Two philosophies: LBYL (“look before you leap”) checks preconditions; EAFP (“easier to ask forgiveness than permission”) attempts the operation and handles failure. Python prefers EAFP because it avoids race conditions between the check and the action:

# LBYL: the file could vanish between the check and the open
if os.path.exists(path):
    open(path)
# EAFP: one atomic attempt
try:
    open(path)
except FileNotFoundError:
    ...

Define custom exceptions by subclassing Exception so callers can catch your errors specifically. Do not use bare except:; it also swallows KeyboardInterrupt and SystemExit. Catch the narrowest exception you can handle.

QQuestionWhat is the difference between EAFP and LBYL?
ASolution

LBYL (“look before you leap”) checks preconditions first; EAFP (“easier to ask forgiveness than permission”) attempts the operation and handles the exception. Python prefers EAFP because it avoids a race between the check and the action and usually reads more cleanly.

QQuestionWhat do else and finally do, and why avoid a bare except:?
ASolution

In try/except/else/finally, else runs only if no exception occurred and finally always runs (cleanup). A bare except: catches everything, including KeyboardInterrupt and SystemExit, hiding bugs and preventing a clean exit; catch the specific exception you can handle.

Iterators and generators

The iterator protocol underpins every for loop: an iterable implements __iter__ returning an iterator, and an iterator implements __next__ returning the next value or raising StopIteration. for calls iter() once and next() until StopIteration.

it = iter([10, 20, 30])
print(next(it), next(it))    # 10 20

Generators are the easiest way to write an iterator: any function containing yield returns a generator that produces values lazily, one at a time. This is how Python streams data without holding it all in memory.

def read_lines(path):
    with open(path) as f:
        for line in f:
            yield line.rstrip()

sum(len(line) for line in read_lines("big.txt"))   # constant memory

yield from delegates to another iterable, and generator expressions compose pipelines:

def chain(*iterables):
    for it in iterables:
        yield from it

evens = (x for x in range(100) if x % 2 == 0)
doubled = (x * 2 for x in evens)     # nothing runs until iterated
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.7cm, minimum height=0.6cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (s) at (0,0) {source};
  \node[b, fill=orange!16] (g1) at (2.2,0) {filter};
  \node[b, fill=orange!16] (g2) at (4.4,0) {transform};
  \node[b, fill=green!14] (c) at (6.6,0) {consumer};
  \draw[a] (s) -- (g1); \draw[a] (g1) -- (g2); \draw[a] (g2) -- (c);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (3.3,-0.6) {one item at a time, constant memory};
\end{tikzpicture}
QQuestionWhat is the difference between an iterable and an iterator?
ASolution

An iterable implements __iter__ and can produce an iterator; an iterator implements __next__ and yields values until it raises StopIteration. A list is iterable but not an iterator; iter(list) returns one. Iterators are single-use — once exhausted, they stay exhausted.

QQuestionWhat does yield do, and why use a generator over a list?
ASolution

A function containing yield returns a generator that produces values lazily and suspends between them. Generators use constant memory and can represent infinite or streamed sequences, whereas a list must materialize every element. Use a generator for large or streamed data; a list when you need indexing, length, or repeated passes.

QQuestionList comprehension versus generator expression: when does the difference actually matter?
ASolution

They matter when the input is large or infinite, or when you chain stages. A list comprehension builds the entire result eagerly; a generator expression is lazy and composes into pipelines with constant memory. For small data the difference is negligible and the list’s extra features are convenient.

Lambdas and functional tools

A lambda is an anonymous function limited to a single expression. Its real use is as a short key or callback, not as a replacement for def.

pairs = [("ann", 30), ("bob", 25)]
print(sorted(pairs, key=lambda p: p[1]))          # by age
print(max(pairs, key=lambda p: p[1])[0])          # oldest name

map and filter exist, but a comprehension is usually clearer and faster; functools.reduce folds a sequence into one value.

from functools import reduce
nums = [1, 2, 3, 4]
print(list(map(lambda x: x * 2, nums)))
print(list(filter(lambda x: x % 2 == 0, nums)))
print(reduce(lambda a, b: a + b, nums))           # 10

functools supplies the practically important tools: lru_cache for memoization, partial to pre-bind arguments, and reduce:

from functools import lru_cache, partial

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

add = lambda a, b: a + b
add10 = partial(add, 10)
QQuestionWhat is a lambda, and when should you use one?
ASolution

A lambda is an anonymous function limited to a single expression. Its practical use is a short throwaway key= or callback (sorted(xs, key=lambda p: p[1])). For anything non-trivial or reused, define a named function: it is testable and inspectable.

QQuestionWhat does functools.lru_cache do?
ASolution

It memoizes a function’s results, keyed by its arguments, turning exponential recursion (such as naive Fibonacci) into linear work. It requires hashable arguments, and the cache is unbounded unless you set maxsize.

Decorators

A decorator is a callable that takes a function and returns a replacement — usually a wrapper that adds behaviour before or after the original. It works because functions are first-class: @deco above def f is just f = deco(f).

import functools, time

def timed(fn):
    @functools.wraps(fn)                 # preserve __name__, __doc__
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = fn(*args, **kwargs)
        print(f"{fn.__name__} took {time.perf_counter() - start:.4f}s")
        return result
    return wrapper

@timed
def work(n):
    return sum(range(n))

work(1_000_000)
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=2.4cm, minimum height=0.7cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=green!14] (call) at (0,0) {call f(x)};
  \node[b, fill=orange!16] (wrap) at (3.2,0) {wrapper};
  \node[b, fill=blue!10] (orig) at (6.4,0) {original f};
  \draw[a] (call) -- (wrap); \draw[a] (wrap) -- node[above, font=\scriptsize] {before/after} (orig);
\end{tikzpicture}

A decorator that takes arguments returns a decorator, adding one more layer:

def repeat(times):
    def deco(fn):
        @functools.wraps(fn)
        def wrapper(*a, **k):
            return [fn(*a, **k) for _ in range(times)]
        return wrapper
    return deco

@repeat(3)
def hello():
    return "hi"

functools.wraps is not optional: without it, the wrapped function loses its name, docstring, and signature introspection. Common real uses are caching (@lru_cache), timing, logging, rate limiting, authentication, and web-framework route registration (@app.route("/")).

QQuestionWhat is a decorator, and how does it work?
ASolution

A decorator is a callable that takes a function and returns a replacement, usually a wrapper that adds behaviour. Because functions are first-class, @deco above def f is exactly f = deco(f). Decorators with arguments add one more layer (a function returning a decorator).

QQuestionWhy is functools.wraps important in a decorator?
ASolution

Without it, the wrapper replaces the original function’s __name__, __doc__, and signature, which breaks introspection, logging, and frameworks. @functools.wraps(fn) copies that metadata onto the wrapper.

Context managers

A context manager guarantees setup and teardown around a block, even if the block raises. It is the with statement, and it is how Python expresses deterministic cleanup (files, locks, transactions, connections).

with open("data.txt") as f:      # f is closed even on error
    contents = f.read()

Under the hood, with calls __enter__ on entry and __exit__ on exit, passing any exception to __exit__ (whose return value decides whether to suppress it).

class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self
    def __exit__(self, exc_type, exc, tb):
        print(f"elapsed {time.perf_counter() - self.start:.4f}s")
        return False          # do not suppress exceptions

contextlib.contextmanager turns a generator into a context manager — everything before yield is setup, everything after is teardown:

from contextlib import contextmanager

@contextmanager
def opened(path):
    f = open(path)
    try:
        yield f
    finally:
        f.close()
QQuestionWhat is a context manager, and why use with?
ASolution

A context manager guarantees setup and teardown around a block, running cleanup even if the block raises. with calls __enter__ on entry and __exit__ on exit, so resources such as files, locks, and connections are always released deterministically.

QQuestionHow do you write a context manager without a class?
ASolution

Use @contextlib.contextmanager on a generator: everything before yield is setup, the yielded value is bound by as, and everything after yield (in a finally) is teardown.

Object-oriented programming

A class is a blueprint; an instance is a concrete object. Attributes are looked up on the instance, then its class, then base classes. self is the instance passed to methods explicitly.

class Account:
    kind = "bank"                     # class attribute, shared
    def __init__(self, owner, balance=0):
        self.owner = owner            # instance attributes, per object
        self.balance = balance
    def deposit(self, amount):
        self.balance += amount

Inheritance reuses and specializes behaviour; super() calls the next class in the method resolution order (MRO), which Python computes with the C3 linearization so that multiple inheritance stays consistent.

class Savings(Account):
    def __init__(self, owner, balance=0, rate=0.02):
        super().__init__(owner, balance)
        self.rate = rate
    def add_interest(self):
        self.deposit(self.balance * self.rate)
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=2.2cm, minimum height=0.62cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (a) at (0,0) {Account};
  \node[b, fill=green!14] (s) at (-1.6,-1.0) {Savings};
  \node[b, fill=orange!16] (c) at (1.6,-1.0) {Checking};
  \draw[a] (a) -- (s); \draw[a] (a) -- (c);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.5) {MRO decides which method wins};
\end{tikzpicture}

Encapsulation in Python is by convention: a leading underscore (_internal) signals “private”, and a double underscore (__secret) triggers name mangling (_Class__secret) to avoid accidental clashes in subclasses. There is no enforcement.

Properties expose a method as an attribute, letting you add validation or computed values without changing the caller:

class Temperature:
    def __init__(self, celsius):
        self._c = celsius
    @property
    def fahrenheit(self):
        return self._c * 9 / 5 + 32
    @fahrenheit.setter
    def fahrenheit(self, value):
        self._c = (value - 32) * 5 / 9

Dunder methods let your objects integrate with the language: __str__/__repr__ for display, __eq__ and __hash__ for equality and dict keys, __len__, __iter__, and arithmetic operators. @classmethod receives the class, @staticmethod receives nothing, and @dataclass generates __init__, __repr__, and __eq__ for data-holding classes.

from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: int
    y: int

print(Point(1, 2) == Point(1, 2))   # True, generated __eq__
QQuestionWhat is the difference between __str__ and __repr__?
ASolution

__repr__ is the unambiguous developer representation, ideally one that could recreate the object; __str__ is the readable user-facing string. print and f-strings use __str__; the interactive prompt and containers use __repr__. If you define only one, define __repr__.

QQuestionWhat is the MRO, and what does super() do?
ASolution

The method resolution order is the linearization of a class’s base classes (C3) that Python searches for attributes. super() delegates to the next class in that order, which is essential for cooperative multiple inheritance and correct __init__ chaining.

QQuestionWhat is the difference between @classmethod and @staticmethod?
ASolution

A classmethod receives the class (cls) as its first argument and is typically an alternative constructor; a staticmethod receives nothing extra and is just a function namespaced in the class. Both are called on the class or an instance.

QQuestionHow does encapsulation work in Python?
ASolution

By convention: a single leading underscore (_x) means “internal”, and a double leading underscore (__x) triggers name mangling to _Class__x to avoid clashes in subclasses. Nothing is truly private — Python trusts the programmer and documents intent.

Modules, packages, and environments

A module is a .py file; a package is a directory of modules (traditionally with __init__.py). import executes the module once and caches it in sys.modules, which is why module-level code runs on first import only.

import math
from math import sqrt
from .utils import helper        # relative import inside a package

The if __name__ == "__main__": guard runs startup code only when the file is executed directly, not when imported — the standard way to make a module both importable and runnable.

def main():
    ...

if __name__ == "__main__":
    main()

Virtual environments isolate each project’s dependencies. Create one with python -m venv .venv, activate it, and install with pip. Modern tools manage dependencies and lockfiles declaratively in pyproject.toml: uv (fast, all-in-one), Poetry, Pipenv, and pdm. Pipelines differ, but the goal is the same: reproducible environments.

python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt      # or: uv sync / poetry install
QQuestionWhat does if __name__ == "__main__": do?
ASolution

It runs its block only when the file is executed directly, not when it is imported. __name__ is "__main__" for the entry-point script and the module’s name when imported. It is the standard way to make a file both importable and runnable.

QQuestionWhy use a virtual environment?
ASolution

To isolate each project’s dependencies and Python version, avoiding conflicts between projects that need different versions of the same package. Create one with python -m venv .venv (or uv venv) and install into it; record dependencies in pyproject.toml/a lockfile for reproducibility.

Static typing

Python is dynamically typed, but type annotations document intent and enable static checkers. They are not enforced at runtime (without a tool).

def greet(name: str, times: int = 1) -> str:
    return (f"hi {name}\n" * times).rstrip()

from typing import Optional, Union, Iterable
def first(items: Iterable[int]) -> Optional[int]:
    return next(iter(items), None)

Modern syntax uses builtin generics (list[int], dict[str, int], int | None) and typing adds Protocol (structural typing), TypeVar (generics), and Literal. Checkers — mypy, pyright, pyre — catch type errors before runtime; run them in CI. Pydantic goes further and validates data at runtime against annotations, which is why it underpins FastAPI.

from pydantic import BaseModel

class User(BaseModel):
    id: int
    email: str
    age: int | None = None

User(id="1", email="a@b.com")     # coerces "1" -> 1 and validates
QQuestionAre Python type hints enforced at runtime?
ASolution

No. Annotations are metadata; Python does not raise if a value violates its annotation. Enforcement comes from external static checkers (mypy, pyright, pyre) at development/CI time, or from runtime validators such as Pydantic.

QQuestionWhat is Pydantic used for?
ASolution

It validates and coerces data at runtime against type annotations, producing typed objects or clear errors. It is the serialization/validation layer behind FastAPI and a common way to parse configuration and API payloads safely.

Concurrency and parallelism

The one theory to internalize is the GIL (Global Interpreter Lock): CPython allows only one thread to execute Python bytecode at a time. The consequences drive every choice:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=2.3cm, minimum height=0.66cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=orange!16] (q) at (0,0) {what is the bottleneck?};
  \node[b, fill=blue!10] (cpu) at (-2.6,-1.2) {CPU-bound};
  \node[b, fill=green!14] (io) at (2.6,-1.2) {I/O-bound};
  \node[b, fill=gray!12] (mp) at (-3.4,-2.3) {multiprocessing};
  \node[b, fill=gray!12] (th) at (1.4,-2.3) {threading};
  \node[b, fill=gray!12] (asy) at (3.8,-2.3) {asyncio};
  \draw[a] (q) -- (cpu); \draw[a] (q) -- (io);
  \draw[a] (cpu) -- (mp); \draw[a] (io) -- (th); \draw[a] (io) -- (asy);
\end{tikzpicture}

Threading shares memory, so it needs locks to avoid race conditions. The classic lost-update bug is counter += 1 from several threads, because it is read-modify-write, not atomic.

import threading
lock = threading.Lock()
counter = 0
def bump():
    global counter
    for _ in range(100_000):
        with lock:
            counter += 1

Multiprocessing sidesteps the GIL with separate processes and ProcessPoolExecutor; data crosses process boundaries by pickling, so it has overhead and no shared state by default.

from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as pool:
    results = list(pool.map(cpu_heavy, data))

Asyncio is cooperative concurrency on a single thread: async def coroutines are scheduled by an event loop, and await yields control while waiting. It scales to thousands of concurrent I/O operations with far less overhead than threads.

import asyncio, aiohttp

async def fetch(session, url):
    async with session.get(url) as resp:
        return await resp.text()

async def main(urls):
    async with aiohttp.ClientSession() as s:
        return await asyncio.gather(*(fetch(s, u) for u in urls))

Rules of thumb: threads for blocking I/O with library code you cannot change; asyncio for high-concurrency network services and frameworks like FastAPI; processes for CPU-bound work. Python 3.13+ ships an experimental free-threaded build without the GIL, but the safe design advice today remains: match the tool to the bottleneck.

QQuestionWhat is the GIL, and how does it affect threading?
ASolution

The Global Interpreter Lock lets only one thread execute Python bytecode at a time in CPython. So threads do not speed up CPU-bound work, but they do help I/O-bound work because the lock is released while a thread waits on I/O. For CPU-bound work, use multiprocessing (separate interpreters).

QQuestionThreading vs multiprocessing vs asyncio: how do you choose?
ASolution

Match the tool to the bottleneck. I/O-bound with blocking libraries → threads; high-concurrency network I/O you control → asyncio; CPU-bound → multiprocessing. Threads share memory and need locks; processes do not share state by default and pay pickling overhead; asyncio is single-threaded cooperative concurrency driven by an event loop.

QQuestionWhat is a race condition, and how do you prevent it?
ASolution

A race condition is when the result depends on the timing of concurrent operations, such as two threads doing counter += 1 (a non-atomic read-modify-write) and losing an update. Prevent it with a lock (threading.Lock), an atomic/thread-safe structure, or by avoiding shared mutable state.

Regular expressions

The re module compiles patterns to a small state machine and searches text. Always use raw strings (r"...") for patterns so backslashes reach the regex engine.

import re
pattern = re.compile(r"(\w+)@(\w+)\.com")
m = pattern.search("contact ann@example.com now")
print(m.group(0), m.group(1), m.group(2))    # ann@example.com ann example

print(re.findall(r"\d+", "a1 b22 c333"))      # ['1', '22', '333']
print(re.sub(r"\s+", " ", "a   b  c"))        # "a b c"

Key functions: search (first match anywhere), match (at the start), fullmatch (entire string), findall/finditer, sub, and split. Named groups ((?P<name>...)), non-greedy quantifiers (.*?), and anchors (^, $) cover most real patterns. Compile patterns used in hot loops once.

QQuestionWhy use raw strings for regular expressions?
ASolution

In a normal string, backslash sequences are interpreted by Python ("\d" is not a valid escape and warns; " " is a newline). A raw string (r"\d+") passes backslashes straight to the regex engine, which is almost always what you want for patterns.

QQuestionWhat is the difference between re.search, re.match, and re.fullmatch?
ASolution

search finds the pattern anywhere in the string, match anchors it at the start only, and fullmatch requires the entire string to match. Use search for “contains”, fullmatch for validation, and compile patterns reused in hot loops.

File handling and paths

Open files with with so they always close, and specify an encoding for text.

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")

with open("notes.txt", encoding="utf-8") as f:
    for line in f:                 # streams line by line
        print(line.rstrip())

Modes: r read, w truncate-write, a append, x exclusive-create, b binary, + read/write. pathlib is the modern, cross-platform way to work with paths; glob matches patterns.

from pathlib import Path
p = Path("data") / "logs" / "app.log"
p.parent.mkdir(parents=True, exist_ok=True)
print(p.suffix, p.stem, p.name)
for f in Path(".").glob("**/*.py"):
    ...

For structured data, use the standard library: json for JSON and csv for CSV, both with with and encodings handled explicitly.

QQuestionWhy open files with with instead of open/close?
ASolution

with guarantees the file is closed when the block exits, even on an exception, so you cannot leak file handles. It replaces a try/finally you would otherwise have to write by hand.

QQuestionWhat is pathlib, and how does it differ from glob?
ASolution

pathlib.Path is an object-oriented, cross-platform way to build and manipulate paths (Path("data") / "a.log", .parent, .suffix, .read_text()) and it supports pattern matching via .glob(). The glob module provides similar filename pattern matching as plain functions.

Testing and code quality

Tests are how Python code stays correct as it changes. The standard library has unittest; the community standard is pytest, whose plain assert and fixtures are far less boilerplate.

# test_math.py
import pytest
from mymath import divide

def test_divide():
    assert divide(6, 3) == 2

@pytest.mark.parametrize("a,b,expected", [(6, 3, 2), (9, 3, 3)])
def test_divide_cases(a, b, expected):
    assert divide(a, b) == expected

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError):
        divide(1, 0)

Fixtures provide reusable setup/teardown; doctest runs examples embedded in docstrings; tox runs tests across multiple environments; coverage reports untested lines. Formatting and linting are automated too: black (opinionated formatter), ruff (fast linter + formatter), and yapf. Wire them into CI with the type checkers so style, types, and tests are all enforced.

QQuestionHow does pytest differ from unittest?
ASolution

unittest (stdlib) uses classes and assertEqual methods; pytest uses plain assert, function-based tests, fixtures for setup, @pytest.mark.parametrize for table-driven cases, and a large plugin ecosystem. Pytest also collects and runs unittest tests, so you can migrate gradually.

QQuestionWhat is mocking, and when do you use it?
ASolution

Mocking replaces a dependency (network, clock, database, payment API) with a controllable stand-in so tests are fast, deterministic, and isolated. Patch at the boundary you own and assert the interaction; over-mocking couples tests to implementation details.

The standard library and common packages

You get a lot for free: collections (deque, Counter, defaultdict, namedtuple), itertools, functools, pathlib, json, datetime, re, math, statistics, logging, subprocess, and dataclasses. The third-party ecosystem adds data (numpy, pandas), web (FastAPI, Flask, Django), async HTTP (aiohttp, httpx), and validation (pydantic).

from collections import Counter, defaultdict, deque
print(Counter("abracadabra").most_common(3))
groups = defaultdict(list)
queue = deque([1, 2, 3])
queue.appendleft(0); queue.pop()

For data-structure and algorithm work specifically — complexity, recursion, sorting, and the patterns that recur in interviews — see the full Data Structures & Algorithms course, which uses Python throughout.

QQuestionWhen would you use collections.deque instead of a list?
ASolution

When you need fast appends and pops at both ends. A list’s pop(0)/insert(0, ...) is \(O(n)\) because it shifts elements; deque.appendleft/popleft are \(O(1)\), which makes deque the right choice for queues and sliding windows.

QQuestionWhat are defaultdict and Counter for?
ASolution

defaultdict(list) auto-creates a value on first access, removing membership checks when grouping. Counter counts hashable items and provides most_common, arithmetic, and set-like operations — the tools for frequency questions.

Pitfalls

QQuestionSelf-check

Why does b = a share the list, and how do you actually copy it? When do threads help and when do you need processes?

ASolution

Names are references to objects, so b = a binds both names to the same object; use copy.copy for a shallow copy or copy.deepcopy for nested independence. Threads help I/O-bound work because the GIL is released while waiting, but CPU-bound work is serialized by the GIL, so use multiprocessing (or a free-threaded build) instead.