Search code examples
pythoncomparison

Apply comparison operator from string


I have a class Foo which contains one of math comparison operations op as a string: '<', '>' or '='. Also Foo contains a number val.

class Foo:
  def __init__(self, operation: str, value: int):
    self.op = operation
    self.val = value

In my code I read a number from input and compare it to Foo's class exemplar value using Foo's contained operation:

f = Foo('<', 15)
to_check = int(input())

if f.op == '<':
  if to_check < f.val:
    # ...
elif f.op == '>':
  if to_check > f.val:
    # ...
elif f.op == '=':
  if to_check == f.val:
    #...  

Is there any way to do it simpler or more elegant?


Solution

  • This is more elegant and works just fine :

    class Foo:
    
        def __init__(self, op: str, val: int):
            self.op = op
            self.val = val
    
        def check(self, other):
            if isinstance(other, (int, float)):
                if self.op == '<': return self.val > other
                if self.op == '>': return self.val < other
                if self.op == '=': return self.val == other
                if self.op == '!=': return self.val != other
                if self.op == '>=': return self.val <= other
                if self.op == '<=': return self.val >= other
            return NotImplemented
    

    f.check(other) check the condition of the contained operation and returns it, in other words:

    f = Foo('<', 15)
    if f.check(14):
        print('ok')
    

    The condition is True because 14 is less than 15