Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a max length to a python conditional (if) statement?

I generate a conditional statement using python's (2.7) eval() function like so:

my_list = ['2 > 1','3 > 2','4 > 3']

if eval('(' + ') or ('.join(my_list) + ')'):
    print 'yes'
else:
    print 'no'

In my case, the list is generated by code, my_list comes from a parameter file, and the list is joined with 'or' statements in the conditional expression. The code above prints 'yes'.

It works fine for small lists, but at a certain number of characters in the eval() statement and I get a string error.

Some searching finds these threads that point to a bug:

  • Why is there a length limit to python's eval?

  • segmentation fault in pi calculation (python)

But their max eval() size is much larger than what I found. In my case, I find between 1744 and 1803 characters does the issue begin. I tried this code and it does crash between the two statements

>>> eval("1.0*"*10000+"1.0")
1.0
>>> eval("1.0*"*100000+"1.0")
# segfault here

So, that brings me back to think that it is not eval(), but actually some max on the if statement.

What's another way to conditionally apply the rules in the list that doesn't involve long strings and the eval() function?

Interestingly, I made my_list much bigger:

my_list = ['2 > 1']*1000000

and the code works fine...

like image 908
philshem Avatar asked Apr 17 '15 13:04

philshem


1 Answers

Perhaps I'm missing something but it would seem that:

any(map(eval, my_list))

Does exactly what you'd like.

from itertools import imap

any(imap(eval, my_list)) # Python 2.

This has the nice effect of not evaluating the rest of the list if the first element evals to True (also known as "short-circuit"). This may or may not be what you are after.

Example:

> any(map(eval, ['2 > 1','3 > 2','4 > 3']))
True
like image 53
ereOn Avatar answered Oct 24 '22 07:10

ereOn