Exercise 2: Deduplicating the Constant Pool — Possible Solution ==================================================================== THE FIX ------------------------------ class ChunkDedup(Chunk): def add_constant(self, value): if value in self.constants: return self.constants.index(value) self.constants.append(value) return len(self.constants) - 1 TEST 1 -- 300 pushes of the SAME value ------------------------------ chunk = ChunkDedup() for i in range(300): emit_constant(chunk, 1.0, 1) Result: constants pool size = 1 (not 300) code bytes = 600 (300 x OP_CONSTANT + 300 x index byte) No ValueError -- stays far under the 256-constant ceiling, because only ONE unique value is ever actually stored. TEST 2 -- 300 pushes of 300 DIFFERENT values ------------------------------ chunk2 = ChunkDedup() for i in range(300): emit_constant(chunk2, float(i), 1) Result: fails after 256 constants, same ValueError as the chapter's own non-deduplicated version: "byte must be in range(0, 256)" WHY THIS WORKS AS AN ANSWER ------------------------------ Deduplication doesn't raise the 256 ceiling itself -- it only helps when a program genuinely repeats the same literal value many times, which is common in real code (the literal 0, 1, and empty-string- equivalent values tend to reappear constantly). The ceiling is on DISTINCT constants, not on how many times OP_CONSTANT appears in the instruction stream -- Test 1 shows 300 instructions referencing just 1 stored value without any trouble, while Test 2 shows that once a program genuinely needs more than 256 truly different values, no amount of deduplication saves it; the single-byte operand simply cannot address a 257th distinct entry, no matter how the constants happen to be pushed. This is the honest boundary of the fix: it optimizes the common case (repeated literals) without touching the chapter's own real, structural limitation (a hard cap on how many UNIQUE values one chunk can hold).