King Tech
King Tech

Reputation: 334

Python - Using Strings As A Condition Operator In An If Statements

In Python is it possible to use a string as an operator in an if statement condition?

I would like to have an object with two values and an operator to test them. For Example:

class Condition:
    def __init__(self, value1, operator, value2):
        self.value1 = value1
        self.operator = operator
        self.value2 = value2

    def test(self):
        if self.value1 self.operator self.value2: <- THIS IS NOT CORRECT.
            return True
        else:
            return False

condition = Condition(5, ">", 4)
if condition.test() == True:
    print("passed")
else:
    print("failed")

Thanks.

Upvotes: 0

Views: 1971

Answers (3)

ShadowRanger
ShadowRanger

Reputation: 155363

The operator module provides the various comparators as functions, so you could map from string form to a function to perform the comparison:

import operator

class Condition:

    cmp_to_op = {'==': operator.eq,
                  '!=': operator.ne,
                  '<': `operator.lt,
                  '<=': `operator.le,
                  '>': `operator.gt,
                  '>=': `operator.ge}

    def __init__(self, value1, operator, value2):
        self.value1 = value1
        self.operator = self.cmp_to_op(operator)
        self.value2 = value2

    def test(self):
        # No need for if return True else return False; comparison already returns
        # True or False for normal objects
        return self.operator(self.value1, self.value2)

Upvotes: 1

dan04
dan04

Reputation: 90995

Python's operator module provides functions corresponding to all the built-in operators, so you can write:

import operator

class Condition:
    def __init__(self, value1, op, value2):
        self.value1 = value1
        self.op = op
        self.value2 = value2
    def test(self):
        return self.op(self.value1, self.value2)

condition = Condition(5, operator.gt, 4)

if condition.test():
    print("passed")
else:
    print("failed")

If you want to pass strings instead of the functions, you can use a dict to map them:

import operator

OPERATOR_SYMBOLS = {
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne,
    '>': operator.gt,
    '>=': operator.ge
}

class Condition:
    def __init__(self, value1, op, value2):
        self.value1 = value1
        self.op = op
        self.value2 = value2
    def test(self):
        return OPERATOR_SYMBOLS[self.op](self.value1, self.value2)

condition = Condition(5, '>', 4)

if condition.test():
    print("passed")
else:
    print("failed")

Upvotes: 3

Ghasem Naddaf
Ghasem Naddaf

Reputation: 862

You can use eval('{}{}{}'.format(v1,op,v2))

Upvotes: 1

Related Questions