This limit applies not only to for loops, but to all other blocks of the control flow. The limit for the number of blocks of nested control blocks is defined inside code.h with a constant named CO_MAXBLOCKS :
#define CO_MAXBLOCKS 20
This constant is used to set the maximum size for the stack. Using Python to execute exceptions and loops called blockstack . This restriction is imposed on all frame objects and is shown in frameobject.h :
int blockstack[CO_MAXBLOCKS];
The most likely reason for this limitation is to keep the memory at a normal level when executing nested blocks. This probably looks like the limit Python imposes on recursive calls . This limit can be seen in compile.c :
if (c->u->u_nfblocks >= CO_MAXBLOCKS) { PyErr_SetString(PyExc_SyntaxError, "too many statically nested blocks"); return 0; }
A more specific answer about why Python has this specfic limit and why it cannot get rid of it was provided by Michael Hudson on the 2004 Python mailing list :
Spot included. This is due to the "blockstack", a very internal detail for the Python implementation. We would like to get rid of it (not because we want people to write code with more than 20 nested for the loop :-), but this is not particularly easy (finally: blocks are the biggest problem).
Note that in Python 2.6 and below, breaking the maximum number of nested loops will cause a SystemError not a SyntaxError . This was changed, however, in Python 3 and fixed before Python 2.7, so a SyntaxError will be created SyntaxError . This has been described in # issue 27514 :
Problem # 27514: Making too many statically nested blocks with syntax instead of SystemError.
The reason for this change in exception types was given by Serhiy Storchaka :
[...] SystemError is not an exception that should be thrown. SystemError - these are errors that cannot be performed in the usual case. This should be caused by misuse of the C API or hacking of Python internal components. I think SyntaxError is more suitable in this case [...].
Christian Dean Jul 07 '17 at 2:31 on 2017-07-07 14:31
source share