Master the fundamental concepts of cpython internals through this focused micro-challenge.
CPython reclaims most objects immediately when their refcount hits zero. Every \`PyObject\` header stores \`ob_refcnt\`; \`Py_INCREF\` and \`Py_DECREF\` adjust it under the GIL.
Simple refcounting cannot free reference cycles. CPython adds a generational cycle detector for container objects that opt into tracking.
Rules for extension authors:
For example, \`x = [1, 2]; y = [x]; x.append(y)\` creates a cycle only the cyclic GC can break; refcount alone leaves both lists alive forever.
\`\`\`c Py_INCREF(obj); /* use obj */ Py_DECREF(obj); \`\`\`
Container cycles need the cyclic GC even when refcounting handles acyclic graphs. Tune `gc.set_threshold` only after you understand which objects participate in `gc.get_objects` tracking.
This exercise asks you to explain refcount semantics and cyclic GC's role. You will document when objects free immediately versus when the cycle collector must run.
You will use the same mental model here when reading production interpreter source later in the track. Sketch one concrete input on paper, predict the outcome, then confirm with code. That discipline catches logic errors early and makes debugging far faster when you extend the implementation in follow-on tasks.
Write a C program demonstrating reference counting.
Requirements:
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github