Home > Software engineering >  Is it possible to pass comparison operators as parameters into functions?
Is it possible to pass comparison operators as parameters into functions?

Time:04-04

Is there a way to specify the function in the if condition in the arguments to a function? For example, I want to be able to do something like this:

a = int(input('number between 0 and 5'))
b = >=
def fun1(a, b):
    if a b 0:
        print('...')

CodePudding user response:

Yes, you can use methods from the operator library if you want to use the comparision operator as a parameter to a function -- in this case, you're looking for operator.ge:

import operator
a = int(input('number between 0 and 5'))
b = operator.ge

def fun1(a, b):
    if b(a, 0):
        print('...')

CodePudding user response:

BrokenBenchmark is right, passing a function is the way to achieve this. I wanted to explain a bit of what's happening under the hood.

Since this is passing a function as an argument (Side note: this means python functions are first-class functions), there are two ways we can achieve this: passing a function or a lambda (an inline function). Below are two examples of both.

def b_func(x, y):
    return x >= y

b_lambda = lambda x, y: x >= y

a = int(input('number between 0 and 5'))
def fun1(a, b):
    if b(a, 0):
        print('...')
    
fun1(a, b_func)
fun1(a, b_lambda)
  • Related