Skip to content

    Memory Model & the GIL

    Python · Advanced

    Definition

    Python variables are references to objects; the GIL lets only one thread run Python bytecode at a time.

    Explains mutability bugs and why threads don't speed up CPU work.

    Diagram

    a → [1,2]b → same list

    Flowchart

    Names point to objectsMutable objects change in placeReference counting frees memoryGIL serializes bytecode

    Example: Shared reference

    a = [1, 2]
    b = a
    b.append(3)
    print(a, a is b)

    Output: [1, 2, 3] True

    Key points

    • Use multiprocessing for CPU-bound work
    • Default mutable arguments are shared across calls

    Interview questions

    Why is def f(x=[]) dangerous?

    The same list is reused between calls and accumulates values.

    More Python topics