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)]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With