Weird recursion limiting with generators

These 5000 nested generators work fine, this prints 5000:

it = [0]
for _ in range(5000):
    it = (x+1 for x in it)
print(next(it))

But if I make just one tiny trivial function call in the middle like this:

def true():
    return True

it = [0]
for i in range(5000):
    if i != 2500:
        it = (x+1 for x in it)
    else:
        it = (x+1 for x in it if true())
print(next(it))

Then I get a RecursionError:

Traceback (most recent call last):
  File "/workspaces/cpython/benchmark.py", line 10, in <module>
    print(next(it))
          ~~~~^^^^
  File "/workspaces/cpython/benchmark.py", line 7, in <genexpr>
    it = (x+1 for x in it)
                       ^^
  File "/workspaces/cpython/benchmark.py", line 7, in <genexpr>
    it = (x+1 for x in it)
                       ^^
  File "/workspaces/cpython/benchmark.py", line 7, in <genexpr>
    it = (x+1 for x in it)
                       ^^
  [Previous line repeated 2496 more times]
  File "/workspaces/cpython/benchmark.py", line 9, in <genexpr>
    it = (x+1 for x in it if true())
                       ^^
RecursionError: maximum recursion depth exceeded

Note the “Previous line repeated 2496 more times”.

So apparently Python does count the recursive iteration towards the recursion limit (1000 by default), but lets me go far beyond the limit, unless I dare to make a call, and then it snaps at me.

This doesn’t seem right. Is that intentional / desirable?

(Both with 3.13.0 and with 3.16.0a2.)

It’s not the function call. This also triggers RecursionError:

it = [0]
for i in range(5000):
    if i != 2500:
        it = (x+1 for x in it)
    else:
        it = (x+1 for x in it)
print(next(it))

The RecursionError is not surprising. A generator is akin to a little function, and thousands of nested function calls can trigger that.

What’s surprising is that there’s no RecursionError in your first example.
I tried replacing 5000 with 50_000_000. It still runs on 3.14.8.

More data points: Python 3.10.12 triggered RecursionError at the expected depth 1000. Python 3.11.8 crashed.

Whenever you find something surprising that’s different between Python versions, a good place to start is the What’s New. You’ve noticed that there’s a difference between 3.14 and 3.10, possibly 3.11, so every change from 3.11 (maybe), 3.12, 3.13, or 3.14 is potentially relevant.

For something like this, searching those pages for “generator” and “recursion” would be a good start (though I would search for “recursi” so that it also catches “recursive”). I did exactly that, and came up with something in the very earliest version:

Now, I can’t say for certain that these generators are getting inlined, but it’s absolutely plausible. You’d have to do further checks to be sure.

Generally speaking, the recursion limit (and RecursionError when you blow past it) is an alternative to outright crashing, rather than being a restriction that you can impose on arbitrary code. If you want to enforce some sort of limit, you may need to look to other tools; it’s possible that audit hooks can do what you want, or maybe spin off a subprocess. But personally, the only reason that I would need to be concerned about this change in behaviour is if I had to support 3.10 and also had something deeply recursive.

Interesting. And I confirm that that gets me an error, too.

But I do think calls, specifically Python function calls, do play a role. I had also done it as follows (results from 3.13.0):

No error, prints 5000:

it = [0]
for i in range(5000):
    it = (x+1 for x in it if x != 2500 or True)
print(next(it))

No error, prints 5000:

true = [True].pop

it = [0]
for i in range(5000):
    it = (x+1 for x in it if x != 2500 or true())
print(next(it))

Error around depth 2500:

def true():
    return True

it = [0]
for i in range(5000):
    it = (x+1 for x in it if x != 2500 or true())
print(next(it))

Yes, the weirdness is that Python does count the recursion and does knowingly let me exceed the limit by far.

Also fine (at least in the sense of not raising RecursionError):

it = [0]
for i in range(5000):
    if i % 2:
        it = (x + 1 for x in it)
    else:
        it = (x + 1 for x in it)
print(next(it))

This appears to have to do with bytecode specialization, and it smells like a bug to me.

I ran this function:

def f():
    it = [0]
    for i in range(5000):
        if i != 2500:
            it = (x+1 for x in it)
        else:
            it = (x+1 for x in it)
    print(next(it))

And then disassembled it:

>>> dis.dis(f, adaptive=True)
  1           RESUME_CHECK             0

  2           LOAD_SMALL_INT           0
              BUILD_LIST               1
              STORE_FAST               0 (it)

  3           LOAD_GLOBAL              1 (range + NULL)
              LOAD_CONST               1 (5000)
              CALL                     1
              GET_ITER                 0
      L1:     FOR_ITER_RANGE          28 (to L3)
              STORE_FAST               1 (i)

  4           LOAD_FAST_BORROW         1 (i)
              LOAD_CONST               2 (2500)
              COMPARE_OP_INT         119 (bool(!=))
              POP_JUMP_IF_FALSE       11 (to L2)
              NOT_TAKEN

  5           LOAD_CONST               3 (<code object <genexpr> at 0x102ccc580, file "<python-input-0>", line 5>)
              MAKE_FUNCTION
              LOAD_FAST_BORROW         0 (it)
              CALL_PY_EXACT_ARGS       0
              STORE_FAST               0 (it)
              JUMP_BACKWARD_NO_JIT    20 (to L1)

  7   L2:     LOAD_CONST               4 (<code object <genexpr> at 0x102ad3aa0, file "<python-input-0>", line 7>)
              MAKE_FUNCTION
              LOAD_FAST_BORROW         0 (it)
              CALL                     0
              STORE_FAST               0 (it)
              JUMP_BACKWARD_NO_JIT    30 (to L1)

  3   L3:     END_FOR
              POP_ITER

  8           LOAD_GLOBAL              3 (print + NULL)
              LOAD_GLOBAL              5 (next + NULL)
              LOAD_FAST_BORROW         0 (it)
              CALL                     1
              CALL                     1
              POP_TOP
              LOAD_COMMON_CONSTANT     7 (None)
              RETURN_VALUE

Disassembly of <code object <genexpr> at 0x102ccc580, file "<python-input-0>", line 5>:
  --           RESUME_CHECK             4

   5           LOAD_FAST                0 (.0)
               GET_ITER_SELF            0
               RETURN_GENERATOR
               POP_TOP
       L1:     RESUME_CHECK             0
       L2:     FOR_ITER_GEN            14 (to L3)
               STORE_FAST_LOAD_FAST    17 (x, x)
               LOAD_SMALL_INT           1
               BINARY_OP                0 (+)
               YIELD_VALUE              0
               RESUME                   9
               POP_TOP
               JUMP_BACKWARD           16 (to L2)
       L3:     END_FOR
               POP_ITER
               LOAD_COMMON_CONSTANT     7 (None)
               RETURN_VALUE

  --   L4:     CALL_INTRINSIC_1         3 (INTRINSIC_STOPITERATION_ERROR)
               RERAISE                  1
ExceptionTable:
  L1 to L4 -> L4 [2] lasti

Disassembly of <code object <genexpr> at 0x102ad3aa0, file "<python-input-0>", line 7>:
  --           RESUME_CHECK             4

   7           LOAD_FAST                0 (.0)
               GET_ITER                 0
               RETURN_GENERATOR
               POP_TOP
       L1:     RESUME_CHECK             0
       L2:     FOR_ITER                14 (to L3)
               STORE_FAST_LOAD_FAST    17 (x, x)
               LOAD_SMALL_INT           1
               BINARY_OP                0 (+)
               YIELD_VALUE              0
               RESUME                   9
               POP_TOP
               JUMP_BACKWARD           16 (to L2)
       L3:     END_FOR
               POP_ITER
               LOAD_COMMON_CONSTANT     7 (None)
               RETURN_VALUE

  --   L4:     CALL_INTRINSIC_1         3 (INTRINSIC_STOPITERATION_ERROR)
               RERAISE                  1
ExceptionTable:
  L1 to L4 -> L4 [2] lasti

(This is with Python 3.15.2)
What I see is that FOR_ITER is replaced by FOR_ITER_GEN in one of the generators. I’m guessing FOR_ITER_GEN is missing a check for if it exceeded the recursion limit? (similar issue to gh-132744 and gh-137883)

Makes me yet again wish that Python would finally get rid of the artificial limit. Back when it was there for preventing crashes due to C stack overflow, it was somewhat acceptable. But now that it can do deep recursion without C stack, it’s between annoying and infuriating. One thing I like about Python is that ints simply grow as large as needed, so I don’t have an artificial limit like 32 bits that I need to care about. I wish Python had the same mindset about recursion. Many things are naturally recursive and I want to do them that way, without an artificial limit screwing it up. Recently for example in more-itertools I saw that natural pretty four lines of recursion got replaced by 22 lines of iterative mess. That’s not good.

You mean like how it DOESN’T raise that exception on 3.15?

Like it currently doesn’t for that particular code. It does for other code, and I worry this will get “fixed” by adding a check that then does it for that code, too.

The recursion limit is there to prevent crashes. The reason it isn’t throwing it here is that the calls are being inlined, meaning that there isn’t a limit, and so, there’s no risk of a crash.

If anything changes along those lines, it’s more likely to be other things optimizing away recursion, and thus fewer RecursionErrors.

What do you mean with “there isn’t a limit”? And are you saying that in the other variations, the calls aren’t inlined? Even the following, where I solely changed the base from [0] to map(lambda x: x, [0]), gives me RecursionError. Does that prevent the inlining of everything else?

it = map(lambda x: x, [0])
for _ in range(5000):
    it = (x+1 for x in it)
print(next(it))

Did you read the patch notes? They can probably explain better than I can.

Which ones?

I linked to them above, as part of the most basic research into what’s changed between versions.

I’ve read the “What’s new” you linked to, and the issue it links to.

That “What’s New” that you linked also says that the inlining means recursive functions can recurse significantly deeper “if the user increases the recursion limit with sys.setrecursionlimit()”. So I really don’t get what you mean with “the calls are being inlined, meaning that there isn’t a limit”.