Now Pair With an AI
Step 1: You already built this solo
You just built the Memory Profiler for an Earlier Project yourself, unaided. That project is unchanged — this page is additive. Now the same project gets built a second way: by prompting an AI assistant, and then reviewing what it hands back with the same skepticism you'd bring to a coworker's pull request.
Step 2: Now pair with an AI
Here's a real prompt a learner could give an AI assistant to build the same memory profiler — an extended version of the prompt from the profile_function() box on the main project page:
Write a Python memory profiler using only the standard library
(tracemalloc, sys). I need:
1. profile_function(func) — takes a zero-argument callable, measures
its peak memory with tracemalloc, and returns the top 3 memory
allocations by source line plus the peak byte count.
2. A comparison between a "heavy" version of a function that builds a
list of 5,000 record dicts, and an "optimized" version using
__slots__ instead of plain dicts for each record, to see which uses
less memory.
3. A formatted text report showing both versions' peak memory and
which one is smaller.
Keep it to one file, no third-party packages, and make sure the
numbers you report are trustworthy.
And here's a plausible response — the kind of code an AI assistant might hand back on the first try. Read it as if it just landed in a pull request from a teammate, before scrolling to the critique below.
import tracemalloc
import sys
def profile_function(func):
"""Profile a zero-argument function's memory usage."""
tracemalloc.start()
result = func()
tracemalloc.stop()
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics("lineno")
top_allocations = [str(stat) for stat in top_stats[:3]]
return {
"result": result,
"top_allocations": top_allocations,
}
class RecordSlotted:
"""Optimized record using __slots__ to save memory per instance."""
__slots__ = ("id", "score")
def __init__(self, id, score):
self.id = id
self.score = score
class TimestampedRecord(RecordSlotted):
"""A timestamped variant of the optimized record, for reports that
need to track when each row was loaded."""
def __init__(self, id, score, loaded_at):
super().__init__(id, score)
self.loaded_at = loaded_at
def load_records_heavy(n):
"""Heavy version: a list of plain dicts, one per record."""
return [{"id": i, "score": (i * 7) % 101} for i in range(n)]
def load_records_optimized(n):
"""Optimized version: a list of __slots__-based objects instead
of dicts -- much less memory per instance."""
return [TimestampedRecord(i, (i * 7) % 101, loaded_at="2026-01-01") for i in range(n)]
def compare_versions(n=5000):
heavy_profile = profile_function(lambda: load_records_heavy(n))
optimized_profile = profile_function(lambda: load_records_optimized(n))
heavy_size = sys.getsizeof(heavy_profile["result"])
optimized_size = sys.getsizeof(optimized_profile["result"])
smaller = "optimized" if optimized_size < heavy_size else "heavy"
report = []
report.append("=== Memory Profiler Report ===")
report.append(f"Heavy version size: {heavy_size:,} bytes")
report.append(f"Optimized version size: {optimized_size:,} bytes")
report.append(f"Smaller: {smaller}")
return "\n".join(report)
if __name__ == "__main__":
print(compare_versions())
It looks reasonable. It even uses __slots__, exactly as asked. It's also wrong in three separate, genuinely easy-to-miss ways — one of which crashes it outright the moment compare_versions() actually runs.
Step 3: Where did the AI's code lie to you?
Click to see the critique
What it looks like it does: compare_versions() reports "Heavy version size" and "Optimized version size" using sys.getsizeof() on each result list, and picks the smaller one as the winner — looks like a clean, direct memory comparison.
What it actually does: sys.getsizeof() on a list only measures the list object's own overhead (the array of pointers) — it does not include the size of what the list contains. Comparing sys.getsizeof(list_of_dicts) against sys.getsizeof(list_of_slotted_objects) compares two nearly-identical numbers (both are just "a list of 5,000 pointers"), completely missing the actual point of the comparison: how much memory each individual record takes. The prompt specifically asked for trustworthy numbers, and this reports a number that looks meaningful but answers the wrong question.
Why it matters: this would report the two versions as nearly identical in size — silently hiding the real savings __slots__ provides, and giving a false "no real difference" conclusion to anyone who trusts the printed report without checking how it was computed.
The fix: use tracemalloc's get_traced_memory() peak value (which was already being tracked and then thrown away by calling tracemalloc.stop() too early — see Flaw 2) instead of sys.getsizeof() on the outer list, since peak memory captures everything allocated during the whole build, not just the outer container's own overhead.
tracemalloc.stop() is called before the snapshot, crashing the whole report
What it looks like it does: profile_function() calls tracemalloc.stop() and then tracemalloc.take_snapshot() right after — looks like a reasonable "measure, then clean up, then report" order.
What it actually does: tracemalloc.stop() turns tracing off entirely. Calling take_snapshot() after stop() doesn't return an empty result — it raises RuntimeError: the tracemalloc module must be tracing memory allocations to take a snapshot, which propagates straight out of compare_versions() and crashes the whole script before any report is printed. It's an easy mistake to make from reading the two calls' names alone — "stop, then snapshot" sounds like "measure, then clean up" — but the module requires the opposite order.
Why it matters: this isn't a silent correctness bug — it's a hard crash on first run, which usually gets caught fast. But it's exactly the kind of error a learner might "fix" by wrapping the call in a bare try/except that swallows the exception, which would turn a loud, easy-to-diagnose crash into the much worse silent-failure version of this same bug. The right fix addresses the ordering, not the crash.
The fix: call take_snapshot() before tracemalloc.stop() — exactly the ordering used in this chapter's own profile_function() (snapshot, then current/peak reading, then stop).
TimestampedRecord quietly defeats the whole point of __slots__
What it looks like it does: TimestampedRecord(RecordSlotted) inherits from the slotted RecordSlotted class and adds one more attribute, loaded_at — looks like a reasonable extension that stays memory-efficient, since the parent class already declared __slots__.
What it actually does: TimestampedRecord itself declares no __slots__ of its own. In Python, a subclass that omits __slots__ gets a regular __dict__ added back automatically — even when its parent is fully slotted. So every TimestampedRecord instance ends up with both the parent's slot storage and a per-instance __dict__, silently reintroducing the exact per-instance overhead __slots__ was supposed to eliminate. The class "uses __slots__" in the sense that the word appears in the code, but the actual instances being measured don't get the memory benefit at all.
Why it matters: this is the single most common real-world __slots__ mistake — it fails silently (no error, attributes work fine, code runs) and specifically undermines the exact feature (memory savings at scale) the whole exercise was built to demonstrate.
The fix: add __slots__ = ("loaded_at",) to TimestampedRecord itself — every class in an inheritance chain needs its own __slots__ declaration (even an empty one, for a subclass that adds no new attributes) for the memory savings to actually hold all the way down.
Step 4: Your entry for this chapter's playbook
Fill this in for yourself — it's not saved or sent anywhere, just yours to keep (copy it into your own notes before you close this tab).