python

Condensing a Python method that does a different comparison depending on the operator passed


I am trying to write a method that evaluates a statement, but the operator (>, <, =) is sent by the user. I am wondering if there is a easy way to write a more concise method.

The simplified version of the code is:

def comparsion(val1: int, val2: int, operator: str):

    if operator == ">":
        if val1 > val2:
            return True

    elif operator == "=":
        if val1 == val2:
            return True

    elif operator == "<":
        if val1 < val2:
            return True

The only thing that changes in each case is the operator, I am wondering if there is a more efficient way to write this.


Solution

  • Use the operator module, which provides named functions for all the standard operators. Then you can use a dictionary to map from the operator string to the corresponding function.

    from operator import lt, gt, eq
    
    ops = {'<': lt, '>': gt, '=': eq}
    
    def comparsion(val1: int, val2: int, operator: str):
        return ops[operator](val1, val2)