Search code examples
pythonpython-2.7

Storing logical conditions in a dictionary and passing them to if statements


I have a dictionary of logical conditions, i.e. a == 1, that I need to use in an if statement for evaluation. This may not be possible, but I wanted to find out for sure. Sample code:

z = {'var1':['a == 1'],
     'var2':['b == 3']
    }
a = 6
b = 20

#If I use the dictionary value in an if statement like this:

if z['var1']:
    print 'TRUE'
else:
    print 'FALSE'

#It will always evaluate as true.  What I want is for the statement to
#translate into the following form:

if a == 1:
    print 'TRUE'
else:
    print 'FALSE'

I have been searching various permutations on if statements, list comprehensions and string manipulation, but I haven't found results matching this problem. If it is not possible, I'd like to know. If there is a better approach, I'd like to know that as well. Thanks in advance for your answers.


Solution

  • You are trying to store a expression, so it is possible to use the built-in eval() function (you can use exec if you want to play around with statements).

    >>> a = 6
    >>> b = 3
    
    >>> z = {
            'var1':eval('a == 1'),
            'var2':eval('b == 3'),
        }
    
    >>> if z['var1']:
            print "True!"
        else:
            print "False!"
    False!
    
    >>> if z['var2']:
            print "True!"
        else:
            print "False!"
    True!
    

    Note that you need to assign your variables before you create the expressions inside your dictionary, as the expression is evaluated at run-time, so a NameError exception will be raised if the variable doesn't exist in memory.

    >>> eval(foo)
    NameError: name 'foo' is not defined
    

    Also be wary that eval() can be dangerous if you allow users to input arbitrary strings as its argument. More about that here.

    To quickly explain why your original code is always returning True, the boolean expression your if statement is evaluating is a list containing one string. Python evaluates all non-empty sequences as True, so you satisfy the condition and the string TRUE is printed.

    >>> z['var1']
    ['a == 1']
    
    >>> bool(z['var1'])
    True