Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string can be evaluated (with eval()) in Python

Tags:

python

eval

I know that I can try-except with the eval itself, but I want to use it in list_comprehensions or map:

[eval(x) if isevaluable(x) else x for x in some_list]

My driving to do so: I get argument from sys.argv - which can be int\float\built-in-constants (especially True, False, None). I want to casting them all in a simple & clean way.

[Note: safe-eval isn't the issue here (even it's indeed recommended)]

like image 754
alikyos Avatar asked Oct 31 '22 23:10

alikyos


1 Answers

An obvious solution that may or may not work for your particular eval string.

def isevaluable(s):
    try:
        compile(s, "bogusfile.py", "exec")
        return True
    except:
        return False

This compiles the code, checking for syntax errors etc. Will not catch all your logical issues but it will check programmatical issues before shooting it into eval which could cause all kinds of troubles.

I thought of doing:

def isevaluable(s):
    try:
        eval(s)
        return True
    except:
        return False

But remember that then you'll execute your string which might obscure your result putting it into your list.
For instance if your string is rm /tmp/cache.txt which will give a positive result in your isevaluable and a negative result in your [eval(x) ...] because it got removed in the try statement.

In this case, compile() is a better alternative. It probably is in any example.

like image 106
Torxed Avatar answered Nov 13 '22 03:11

Torxed