Why does Python have a limit on the number of static blocks that can be nested?

前端 未结 3 1319
[愿得一人]
[愿得一人] 2020-11-30 03:22

The number of statically nested blocks in Python is limited to 20. That is, nesting 19 for loops will be fine (although excessively time consuming; O(n^19

3条回答
  •  [愿得一人]
    2020-11-30 04:20

    This has to do with the blockstack, which is a stack of the byte code addresses, and is used to execute code blocks such as loops and exceptions.

    It just so happens that a version of C (older than C99) had set this limit to 20, and since the CPython interpreter is built with C, the same convention has been followed:

    #define CO_MAXBLOCKS 20 /* Max static block nesting within a function */
    

    The constant 20 seems to be set out of convention, and nothing more.

    [Links courtesy Christian Dean.]


    Why is the limit 20?

    If the argument of convention isn't convincing, then take a look at The Zen of Python:

    In [4]: import this
    The Zen of Python, by Tim Peters
    
    ...
    Flat is better than nested.
    ...
    

    How can you increase this value?

    Since this value is a hardcoded constant, the only way to change it to effect in your programs is to rebuild your python distribution and run your script on the new build.

    1. Download the cpython source code from github

    2. Navigate to cpython/Include/code.h

    3. Change the value of CO_MAXBLOCKS to anything greater than 20

    4. Recompile Python (disable tests, they'll complain)

提交回复
热议问题