0

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.

3 Answers 3

3

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Works great. Thanks!
1

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

2 Comments

I am going to use what @dan04 suggested but I will keep this in mind if I ever need it in the future. Thanks.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.