Scenario: memory grows after every request
A service's memory usage grows after every distinct request even though handlers finish. Calling garbage collection does not restore the expected baseline. Inspection shows a process-global cache with no maximum size.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 18 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Build a diagnosis from evidence
- Compare a repair with its trade-offs
- Test the changed behaviour
Follow the evidence.
A service's memory usage grows after every distinct request even though handlers finish. Calling garbage collection does not restore the expected baseline. Inspection shows a process-global cache with no maximum size.
Observed evidence
- Growth correlates with distinct keys rather than current active requests.
- Cached results remain strongly referenced.
- Repeated requests for the same small key set plateau.
Investigation sequence
- Measure repeated batches and separate Python allocations from native memory.
- Inspect cache cardinality and reference owners before assuming a collector bug.
- Introduce a bounded cache or expiry policy and test eviction/staleness behaviour.
Challenge the repair
- Test eviction and verify that an evicted key is recomputed correctly.
- Which metrics would distinguish native memory growth from retained Python objects?
Read the incident, not just the error
An object that remains reachable from a long-lived cache is not unused garbage. Finished requests do not automatically release values retained by another owner.
Understand first
Memory growing with distinct keys, but plateauing with repeated keys, suggests retained cache entries. Check the owner and cardinality before blaming the collector.
Words you will see
- Reachable
- Still accessible through references from live program state.
- Cache cardinality
- The number of entries retained by a cache.
- Retention
- Keeping an object alive through a reference beyond its immediate use.
Compare repeated and distinct requests
The model inserts a, a, then b into one mapping. Reassigning a replaces its value rather than adding a second key. The entry counts 1, 1, 2 support the prediction that distinct keys drive cardinality growth.
That observation is evidence about entries, not total process bytes. Values may have different sizes, native libraries may allocate outside Python, and an allocator may retain freed arenas. A cache hypothesis still needs owner inspection and comparable repeated-batch measurements.
Repair the lifetime rather than invoke collection blindly
A live global dictionary strongly references its values. Running garbage collection does not remove a value merely because the request that produced it ended. Remove ownership through eviction, explicit invalidation or a different lifecycle when cached state is no longer needed.
A mapping may grow to O(d) entries for d distinct keys, excluding key and value sizes. A limit trades future recomputation for less retained state. Weak references are not durable storage; values may disappear when no other owner retains them.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
cache = {}Create a live cache owner.
for key in ['a', 'a', 'b']:Compare a repeated key with a distinct key.
cache[key] = key.upper()Retain one value under each unique key.
print(len(cache))Observe entry count rather than pretend to measure bytes.
print(sorted(cache))Display the retained key set in stable order.
A service's memory usage grows after every distinct request even though handlers finish. Calling garbage collection does not restore the expected baseline. Inspection shows a process-global cache with no maximum size.
Conceptual retention path, not a measured heap
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- RootA long-lived mapping remains live.
- ReferenceEach cache entry retains its key and value.
- ReleaseEviction removes this ownership path; other owners may remain.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Use only distinct keys.
Try: Replace the sequence with ['a', 'b', 'c'].
Counts become 1, 2, 3.
Release cache ownership explicitly.
Try: Add cache.clear() before the final print.
The displayed keys become empty; this does not assert that process RSS instantly falls.
Before you move on
If the same ten keys repeat a thousand times, must this dictionary contain ten thousand entries?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. It holds at most those ten distinct keys. That does not prove fixed process memory: value sizes and other owners can still change.
Investigate before changing code
An eviction policy chooses what to forget when capacity is full. Least recently used means remove the entry whose most recent access is oldest.
Understand first
A small working set often benefits from retaining recently used values. A deterministic order model makes the eviction rule testable without measuring memory or timing.
Words you will see
- Eviction
- Removing a cache entry to satisfy a limit.
- Least recently used / LRU
- The entry accessed least recently among those retained.
- Hit
- A lookup that finds a retained entry.
Trace a hit before a new insertion
Start with oldest a, then newest b. Accessing a removes it from its old position and appends it as newest. Adding c then exceeds capacity two, so b leaves. A FIFO queue that ignores hits would instead remove a; that is a different policy.
The list stores keys only. Real cache values belong in a matching storage structure and every hit must update recency consistently. The browser exercise asks for a pure trace result, not a thread-safe cache or a measured allocator model.
Choose a suitable implementation
List remove searches the retained keys, so a trace of n accesses with capacity k can take O(nk) work and O(k) retained keys, plus output copies. It is simple teaching code, not a claim that every LRU cache costs this much.
An ordered mapping or a hash table plus linked order can support efficient average updates under ordinary hash assumptions. A count bound still does not control bytes when values vary. Use a byte policy or an expiry rule when that better matches the incident.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
order = ['a', 'b']Read order as oldest to newest.
order.remove('a')A hit removes a's old position.
order.append('a')Record a as newest.
order.pop(0)After c arrives, evict the oldest remaining key b.
Measure repeated batches and separate Python allocations from native memory. Inspect cache cardinality and reference owners before assuming a collector bug. Introduce a bounded cache or expiry policy and test eviction/staleness behaviour.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Remove recency refresh.
Try: Remove both the remove('a') and append('a') lines.
The result is ['b', 'c'], illustrating FIFO rather than LRU.
Allow three keys.
Try: Change the comparison from > 2 to > 3.
No key is evicted and all three remain in modeled recency order.
Before you move on
After accesses a, b, a, c with capacity two, which key should an LRU model evict?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
b, because the second access to a made a more recent than b. FIFO would evict a, showing why a repeated-hit regression matters.
A repair you can explain
functools.lru_cache can bound memoized function results by entry count. Its cache information and explicit clearing expose useful deterministic policy evidence.
Understand first
The preserved original uses a pure square calculation so cache behavior can be inspected without network calls. It proves an entry bound and invalidation, not a bound on total service memory.
Words you will see
- Memoization
- Remembering a function result for a later call with the same arguments.
- maxsize
- The configured maximum number of retained cache entries.
- Invalidation
- Removing a previously retained result so later work must recompute it.
Read the bound in the original
The decorator wraps calculate with an LRU cache of at most two entries. Calls for 0, 1, 2 and 3 introduce four distinct argument keys, but cache_info().currsize reports only two retained entries.
cache_clear removes retained results and resets cache statistics. The second print reports zero entries. calculate returns integers and owns no external resource, so clearing this fixture does not need a connection-close protocol.
Distinguish retained entries from total bytes
A function returning large objects can retain far more bytes per entry than this square function. Other references may keep an evicted value alive. Cache key hashing, results, wrapper state and allocator behavior all sit outside a simplistic two-entry equals two-bytes claim.
Choose the limit from a workload budget and recomputation cost. Verify a repeated-key plateau, distinct-key eviction and explicit clearing. If freshness matters, an LRU policy alone does not expire old values by age.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
@lru_cache(maxsize=2)Retain at most two argument/result entries.
return value * valueCompute a pure integer result on a miss.
for value in range(4):Visit four distinct integer arguments.
print(calculate.cache_info().currsize)Inspect retained entry count, first two and then zero.
calculate.cache_clear()Remove the cache's retained entries explicitly.
The example proves the configured cardinality bound and explicit invalidation. It does not claim that a real service's total memory is bounded by the cache entry count alone.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Reduce the entry bound.
Try: Set maxsize=1.
The first count becomes one; the count after clearing remains zero.
Request another existing key.
Try: Add calculate(3) after the loop.
The retained count remains two; the repeated call is a hit, not a new distinct entry.
Before you move on
If calculate returns a list containing a million items, does maxsize=2 bound retained items to two?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. It bounds cached argument/result entries to two. Each result may contain many objects, and other owners may retain additional values.
Reproduce growth by controlling key cardinality
Run repeated requests with a fixed small set of keys, then repeat with new keys each time. The incident predicts a plateau in the first experiment and continuing growth in the second because the global cache retains distinct results. Record request count, cache entry count, tracked allocations, and process memory at comparable points. A handler returning successfully only proves its stack frame ended; it does not prove that every object created for the request became unreachable.
Consider competing owners such as callbacks, task registries, exception histories, and native client buffers. Calling garbage collection without inspecting ownership is weak diagnosis because reachable cached values are not garbage. Compare allocation snapshots after equal-sized batches and inspect the structures whose cardinality changes. If Python allocations remain stable while process memory grows, investigate native memory and allocator behavior rather than concluding that an unbounded Python dictionary explains every observed byte.
Trace retention and interpret the cache fixture
A process-global cache holds strong references to keys and results after requests finish. The reference lru_cache has maxsize two, evaluates four distinct squares, and reports a current size of two. Clearing it then reports zero. This demonstrates an entry-count bound and invalidation on a simple pure function. It does not prove immediate operating-system memory release or bound the entire service's memory, which includes active work, libraries, buffers, and other owners.
An entry can retain a large graph, including arguments stored as keys and descendants referenced by a result. Two entries containing large documents are not equivalent to two small integers. A size policy may need estimated byte accounting, input-size limits, or refusal to cache oversized results. Weak references change reachability behavior but are not a durable storage strategy, and not every useful object supports the desired weak-reference pattern.
Repair capacity and freshness as explicit policies
Choose what the cache optimizes and what staleness is acceptable before selecting eviction. LRU limits recent entry count; expiration limits age; a byte budget targets resource usage. These policies solve different problems and may need to coexist. Ensure keys include all context affecting the result, including authorized scope when relevant, so a better memory bound does not introduce cross-user data reuse or return a result computed for incompatible inputs.
Eviction means later requests may recompute and increase latency or downstream load. If many requests miss together, coordinate duplicate work or bound concurrent computations instead of treating capacity reduction as free. A cache of a pure square calculation is much simpler than a cache of mutable remote records. Decide whether callers may mutate cached results, how updates invalidate entries, and whether a shared result needs defensive copying or an immutable representation.
Verify eviction and operational behavior, not just size
Test that an evicted key recomputes the correct value, recently used keys follow the chosen policy, and clear removes retained entries. Include variable-size results, repeated keys, and a high-cardinality workload. For time-based expiration, inject a clock rather than waiting through real intervals. Check error behavior: a failed computation should not become an unexplained permanent cached failure unless that is an intentional negative-caching policy with its own lifetime.
Measure hit rate, misses, evictions, active computations, and memory over repeated bounded workloads after repair. The original symptom should stop growing under the stated input and capacity assumptions, but process memory may not immediately return to its startup level. Keep those claims separate. If the service still grows, repeat the ownership investigation instead of layering forced collections onto every request, which adds work without removing strong references or fixing a retained callback graph.
Transfer question: A cache is limited to 100 entries, yet a few requests still exhaust memory. What additional bounds and tests are needed?
Measure individual key and result sizes, plus the number of simultaneous cache misses. An entry-count bound allows one enormous result, and concurrent in-flight computations can exceed the eventual retained cache size. Limit accepted input and result sizes, apply a byte-aware retention policy where appropriate, and bound active computation. Test one oversized value, many concurrent misses, and repeated hits on a stable small set. Compare Python allocation evidence with native buffers before selecting a tool. Preserve freshness and authorization scope while changing retention; replacing an unlimited cache with a small but incorrectly shared cache is not a valid repair.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Recreate the repair independently
Test eviction and verify that an evicted key is recomputed correctly. Start from the symptoms and write your own regression assertion before opening the reference.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: trace LRU keys without a cache server
Return the final oldest-to-newest key order for a deterministic access trace.
The contract
- accesses is a list of string keys; capacity is a nonnegative integer.
- Return a new list of at most capacity distinct keys, oldest to newest. A hit moves its key to newest; a new key evicts the oldest only when over capacity.
- Capacity zero retains nothing. Empty input returns []. Do not mutate accesses or claim these keys measure memory bytes.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- refresh before eviction
r = lru_keys(['a', 'b', 'a', 'c'], 2) assert type(r) is list and r == ['a', 'c']
- zero capacity
assert lru_keys(['a', 'b'], 0) == []
- empty ownership
x = [] r = lru_keys(x, 3) assert type(r) is list and r == [] and r is not x
- repeated hits
assert lru_keys(['a', 'a', 'a'], 2) == ['a']
- boundary capacity
assert lru_keys(['a', 'b', 'c', 'b'], 3) == ['a', 'c', 'b']
- input preservation
x = ['a', 'b', 'a'] r = lru_keys(x, 1) assert r == ['a'] and x == ['a', 'b', 'a'] and r is not x r.append('z') assert x == ['a', 'b', 'a']
Why does this simple model not advertise constant-time cache operations?
Membership, remove and front pop can scan or shift up to k keys. For n accesses and capacity k it can take O(nk) work with O(k) retained keys. Ordered-map designs can improve updates; this model teaches policy, not throughput.
Guided: remove one cache owner's references
Return an independent filtered cache mapping while leaving the supplied mapping unchanged.
The contract
- cache maps string keys to integer values; removed is a list of string keys to forget.
- Return a new dict keeping entries not named in removed, in their original insertion order. Missing and repeated removal keys have no extra effect.
- Do not mutate either input. All values are immutable integers; no nested mutable copy is required. Empty inputs are valid.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- remove one
r = forget_keys({'a': 1, 'b': 2}, ['a']) assert type(r) is dict and r == {'b': 2} - empty mapping
x = {} r = forget_keys(x, ['a']) assert type(r) is dict and r == {} and r is not x - nothing removed
x = {'a': 0} r = forget_keys(x, []) assert type(r) is dict and r == {'a': 0} and r is not x - duplicates and missing
assert forget_keys({'a': 1, 'b': 2}, ['a', 'x', 'a']) == {'b': 2} - remaining order
r = forget_keys({'z': 1, 'a': 2, 'b': 3}, ['a']) assert type(r) is dict and list(r) == ['z', 'b'] - ownership
x = {'a': 1, 'b': 2} keys = ['a'] r = forget_keys(x, keys) assert type(r) is dict and r == {'b': 2} and r is not x r['b'] = 9 assert x == {'a': 1, 'b': 2} and keys == ['a']
Does this function free objects from the supplied cache?
No: it leaves that owner unchanged and returns a separate filtered mapping. For n cache entries and m removal IDs, ordinary hash behavior gives O(n+m) work and output/set storage. The caller decides when to replace or release its old owner.
Transfer: evict by declared weight, not key count
Apply append-then-evict-oldest to entries whose supplied weights must fit a total budget.
The contract
- entries is a list of (string key, nonnegative integer weight) tuples in arrival order; budget is a nonnegative integer.
- Return a new list after appending each occurrence and evicting oldest entries until the total retained weight is <= budget. Duplicate IDs remain independent arrivals.
- Zero-weight entries fit zero budget. An oversize arrival may evict earlier entries and itself. Preserve input; weights are policy units, not measured Python memory.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- weight eviction
r = weighted_entries([('a', 3), ('b', 4)], 5) assert type(r) is list and r == [('b', 4)] and all(type(x) is tuple for x in r) - exact boundary
assert weighted_entries([('a', 2), ('b', 3)], 5) == [('a', 2), ('b', 3)] - empty ownership
x = [] r = weighted_entries(x, 0) assert type(r) is list and r == [] and r is not x
- zero weights and duplicates
assert weighted_entries([('a', 0), ('a', 0)], 0) == [('a', 0), ('a', 0)] - oversize flush
assert weighted_entries([('a', 2), ('b', 8), ('c', 1)], 5) == [('c', 1)] - preserve arrivals
x = [('a', 4), ('b', 2), ('a', 1)] r = weighted_entries(x, 3) assert type(r) is list and r == [('b', 2), ('a', 1)] and r is not x r.append(('z', 0)) assert x == [('a', 4), ('b', 2), ('a', 1)]
How is this different from maxsize=2, and what does the simple implementation cost?
A two-entry limit ignores their weights; this policy limits their sum. Each entry is appended and evicted once, but front list pops can shift many references, so worst-case work is O(n²), with O(n) retained storage when zero weights fit. A deque can improve eviction mechanics.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneThe underlying mechanism
Eviction releases one owner, not every owner. A caller that keeps a returned mutable result can continue to access it after the cache is cleared.
Understand first
This explains why entry-count drops and actual object lifetimes can differ. It also exposes a separate API question: may callers mutate cached values?
Words you will see
- Strong reference
- A reference that keeps an object alive while it remains reachable.
- Alias
- Another reference to the same object.
- Snapshot
- A copied representation whose intended mutable levels are separate.
Trace the surviving owner
saved and cache['a'] initially refer to one list. Clearing cache removes the mapping's reference, but saved still reaches the list. Appending through saved succeeds and displays the value. No garbage-collector failure is involved.
If the mapping had remained populated, mutation through saved would also change what a cache lookup observes. Choosing immutable values or returning copies can prevent callers from corrupting shared results, but shallow copies only separate the outer container.
Match the repair to the measured owner
Inspect long-lived closures, callbacks and active tasks in addition to the cache. A bounded cache cannot constrain a caller that stores every returned value forever. Distinguish Python-retained objects from native allocations and allocator reservation before attributing a process-memory curve.
Copying a result of m entries adds O(m) work and outer storage. Returning the same result is cheaper but creates shared mutation rules. Neither an exact getsizeof total nor forced collection alone establishes the whole reachable graph's size.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
cache = {'a': [1]}A mapping owns a mutable list.
saved = cache['a']Create another reference to that same list.
cache.clear()Remove only the mapping's ownership path.
saved.append(2)The remaining reference can still edit the live list.
A reachable object is not garbage merely because a request no longer needs it. Callback closures, registries and active tasks can retain entire object graphs. An entry-count bound does not bound bytes when values vary greatly in size.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Protect outer ownership.
Try: Use saved = cache['a'].copy() before clearing.
saved is then a separate list; equal displayed values do not mean shared identity.
Observe sharing before eviction.
Try: Move cache.clear() below print(saved) and print(cache['a']) before clearing.
The cache observes [1, 2] too because the original result was shared.
Before you move on
Would del cache free the list if saved still refers to it?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Removing the cache name removes one path, while saved remains a live owner. The list is still reachable and usable.
Alternatives and operational trade-offs
A byte-budget policy uses declared entry weights rather than entry count. Such a model is useful for policy reasoning but must not pretend its weights are measured heap sizes.
Understand first
Two very large cached values can violate a budget that two tiny values fit. The transfer task changes from recency to caller-supplied weights and explicit eviction.
Words you will see
- Weight
- A supplied nonnegative integer cost for one modeled entry.
- Budget
- The maximum sum of retained weights.
- Oversize entry
- An individual entry whose weight exceeds the whole budget.
Make the quantity and eviction rule explicit
The program supplies two weights, 3 and 4, with budget 5. Their sum 7 exceeds the budget. Removing the oldest entry a leaves b with weight 4. These numbers represent policy units, not Python object measurements.
For the transfer contract, nonnegative weights and budgets are required. Append new entries in arrival order, then evict oldest until total fits. An oversize arrival can evict earlier entries and itself under that rule; rejecting it before admission would be a different valid policy only if explicitly requested.
Recognize the limits
Caller-provided weights can estimate payload sizes but omit keys, containers and shared graphs. Real byte accounting needs an appropriate measurement definition and safety margin. Expiry addresses freshness; count or weight budgets address retained capacity.
Summing k weights costs O(k); repeated list pops from the front shift references. A running total and deque improve a long streaming implementation. The small browser model prioritizes visible transitions over a performance claim.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
entries = [('a', 3), ('b', 4)]Supply entries in oldest-to-newest arrival order.
total = sum(weight for key, weight in entries)Add declared units, not measured object bytes.
key, weight = entries.pop(0)Remove the oldest entry while over budget.
total -= weightKeep the running total consistent with retained entries.
Choose an entry, byte and/or time limit appropriate to the workload. Eviction changes hit rate and latency; expiry changes freshness. Weak-reference caches may discard values unexpectedly and are unsuitable for required durable state.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Fit both entries.
Try: Set budget = 7.
Both remain and total is seven.
Make one arrival oversize.
Try: Use entries = [('a', 8)] with budget = 5.
The entry is evicted, leaving an empty list and total zero.
Before you move on
With budget 5 and a single weight-8 arrival, what happens under append-then-evict-oldest?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The arrival is eventually evicted too, leaving no retained entries. If earlier entries existed they may also have been evicted first. Reject-before-admission would preserve them but is a changed policy.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.