HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

if statements or eval?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
statementsevalstackoverflow

Problem

I'm wondering about the following code:

def ValidateGoto(placeToGo):
    conditions = {}
    conditions["not placeToGo"] = "Enter a positive integer in the text box"
    conditions[
              "int(placeToGo) <= 0"] = "I need a positive integer in the text box please"
    conditions[
           "not DataStore.DBFILENAME"] = "There is no data available in the table"
    for condition, errormessage in conditions.iteritems():
        try:
            if eval(condition):
                print errormessage
                return False
        except ValueError:
                return False
    return True


-
Should the eval statement be avoided?

-
Is this approach justified to reduce the number of if statements?

Solution

You have the right basic idea - pass a list of conditions - but the implementation is wrong.

Yes, you should avoid eval; it is a dangerous source of potential error (and performs poorly as a non-bonus). You might put anything in there. You might not even notice a typo which caused nasty side effects, since Python has a very tolerant definition of truth and will be happy as long as the expression evaluates to something. Instead, why not pass a list of lambda functions? Then you just call each function in turn. Much safer.

For example, you could build a list of tuples (condition, error message) like this:

conditions = [(lambda: not placeToGo, "Enter a positive integer in the text box"),
(lambda: int(placeToGo) <= 0, "I need a positive integer in the text box please"),
(lambda: not DataStore.DBFILENAME, "There is no data available in the table")]


And then iterate through the list, calling each function in turn.

If you are not familiar with functional programming (in Python or any other language), take a look at this short tutorial

Code Snippets

conditions = [(lambda: not placeToGo, "Enter a positive integer in the text box"),
(lambda: int(placeToGo) <= 0, "I need a positive integer in the text box please"),
(lambda: not DataStore.DBFILENAME, "There is no data available in the table")]

Context

StackExchange Code Review Q#38825, answer score: 7

Revisions (0)

No revisions yet.