Search code examples
pythoneval

Python EVAL() - AND statements


I am trying to use EVAL() to evaluate two statements at the same time but I am having some issues:

metrics_dict = {}

def testA(n):
    print ("testA done")
    global metrics_dict
    result = n**n
    metrics_dict["metricA"] = result
    return result

def testB(n):
    print ("testB done")
    global metrics_dict
    result = n**n
    metrics_dict["metricB"] = result
    return result

def testC(n):
    print ("testC done")
    global metrics_dict
    result = n**n
    metrics_dict["metricC"] = result
    return result

logic = "testA(2) > 10 and testB(3) > 0"

if I run the eval on "logic", like this:

x = eval(logic)

I get "testA done" and FALSE, and I believe this happens because since testA is FALSE, the EVAL() does not proceed with the second check for testB, in addition to that my metrics_dict only has metricA in it, so my question is, is there a way to force the eval to go over all the checks within my logic statement, I need to be able to check and record both tests all the the time, it does not matter if it is a FALSE, FALSE or FALSE, TRUE or TRUE, FALSE or TRUE, TRUE.

thaks all


Solution

  • Rather than messing with eval, where you're not going to be able to sidestep how AND works logically, you should consider encoding your check logic as a collection of independent statements:

    >>> logic = [testA(2) > 10, testB(3) > 0]
    testA done
    testB done
    >>> logic
    [False, True]
    

    And then you can still get your end result via all(logic) or some other such reduction.