Monday, August 11, 2008

The interesting python function called eval

What did I do
I have this Mini Project as my assignment, which I decide to use python. The assignment require that we have to design a program. And implement it.
Which during the implementation phase, I cheat a little. Actually a lot.

We have to create a calculator, which it need something quite advance, like doing calculus, and  like evaluate 1+2+3. So i decide to cheat  a little by, using sympy to do advance stuff(more on that later, it is good). Another way I cheat is, have all the function, which is not really a cheat, that is I use eval. Which goes to the main story.

eval() that's interesting
eval() is a interesting function, because it takes a string and runs it as python expression. But the catch is, the string must the a valid python expression. For example,in python intrepreter:
>>> eval("1+2+3")
Would evaluate 6. You can call functions:
>>>eval("somefunction()")
But built in function like print, doesn't work . So there is some catch. Some built in function, doesn't seems to work.

I actually use it, because, I get the input in form of string, so a 1+2+3, would look like "1+2+3", which is a string. After I validate, I can just use the string with eval(), to actually execute it.

The danger
Then I realize one thing, eval is powerful, but, it is also a risk, I just realize that, since I am using django(don't ask), it is possible for someone to execute, a command to delete the database(for example). If we are not carefull, it is possible for it to execute system command, using popen. A tried and work example:
eval("popen('ls')")
 Luckily it is just ls, imagine it is something else. On the other hand, it can be handled with proper permission setting. It might also be attempt, in accessing databases.

Conclusion
So if the system is open to other people, try to avoid the eval. Like in django, or actually all applications, other might use.

But I can't help but to think that, such powerful feature exist, is pretty cool.

No comments:

Post a Comment