Search code examples
pythoneval

Why is there a limit on the eval function?


Why does an error occur in this code when the number of range increases? He's working at 92, and you can't bet any more.

import random
from random import randint
masz = []
pmasz = '('
n = 0
for i in range(92):    
    masz.append(str(randint(-10000, +10000)))   
    masz.append(random.choice(['+', '-', '*', '/'])) 
    pmasz += masz[n] +")" + masz[n+1]
    n += 2 
print(eval((n//2-1)*"("+pmasz[:-1]))

Solution

  • The problem is due to overly deep parentheses nesting. This is a known issue that probably won't be fixed. You can read the details here.

    You can avoid the problem by evaluating intermediate results to limit the nesting depth.

    I also suggest using ast.literal_eval, which is safer then using eval.