Using eval to use a string as comparison

I am just writing a little compiler and interpreter and I have a method to check if 2 values are equal, not equal greater and so on. My code looked something like this

if typeOfCompare == "==":
return firstVal == secondVal

elif typeOfCompare == "!=":
return firstVal != secondVal

elif typeOfCompare == "<=":
return firstVal <= secondVal

....
But this was quite inflexible and I didn't like all the returns. As the type of the comparison was already checked by the parser I came up with a simpler method
return eval(str(firstVal) + typeOfCompare  + str(secondVal))
This might be a performance hit and not as clear but its easier to code and more extensible. You got to love python enabling something like this using a string as comparison operator.

No comments: