Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an operator to a python function?

I'd like to pass a math operator, along with the numeric values to compare, to a function. Here is my broken code:

def get_truth(inp,relate,cut):         if inp print(relate) cut:         return True     else:         return False 

and call it with

get_truth(1.0,'>',0.0) 

which should return True.

like image 317
philshem Avatar asked Sep 03 '13 11:09

philshem


People also ask

How do you pass an operator in Python?

Python pass StatementThe pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed. Empty code is not allowed in loops, function definitions, class definitions, or in if statements.

Can you pass a list into a function Python?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

What is the operator == in Python?

Python is operator vs == operator The equality operator ( == ) compares two variables for equality and returns True if they are equal. Otherwise, it returns False . Since a and b references the same object, they're both identical and equal. In the following example, both lists have the same elements, so they're equal.


2 Answers

Have a look at the operator module:

import operator get_truth(1.0, operator.gt, 0.0)  ...  def get_truth(inp, relate, cut):         return relate(inp, cut)     # you don't actually need an if statement here 
like image 129
grc Avatar answered Oct 09 '22 07:10

grc


Make a mapping of strings and operator functions. Also, you don't need if/else condition:

import operator   def get_truth(inp, relate, cut):     ops = {'>': operator.gt,            '<': operator.lt,            '>=': operator.ge,            '<=': operator.le,            '==': operator.eq}     return ops[relate](inp, cut)   print(get_truth(1.0, '>', 0.0)) # prints True print(get_truth(1.0, '<', 0.0)) # prints False print(get_truth(1.0, '>=', 0.0)) # prints True print(get_truth(1.0, '<=', 0.0)) # prints False print(get_truth(1.0, '==', 0.0)) # prints False 

FYI, eval() is evil: Why is using 'eval' a bad practice?

like image 41
alecxe Avatar answered Oct 09 '22 08:10

alecxe