How to Pass an Operator to a Python Function

How to pass an operator to a python function?

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

Is it possible to pass comparison operators as parameters into functions?

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('...')

How can I pass functions or operators as arguments to a function in Python?

In Python, functions are first-class, which is to say they can be used and passed around like any other values, so you can take a function:

def example(f):
return f(1) + f(2)

To run it, you could define a function like this:

def square(n):
return n * n

And then pass it to your other function:

example(square)  # = square(1) + square(2) = 1 + 4 = 5

You can also use lambda to avoid having to define a new function if it's a simple expression:

example(lambda n: n * n)

Passing operators as function parameter

Basically under the hood it is overriding the default implementation of __eq__ and mapping the table/row names into a SQL friendly string format that can be a part of a bigger query.

You can refer to How is __eq__ handled in Python and in what order? which has some other great answers to help understand more what’s going on here.

Without delving into the source code (and possibly making it more confusing, if not the links are below) I made a mock-up class to demonstrate the basic premise behind what it’s doing and that it can easily done with other classes as well. (Please take this as only an example and nothing close to what it exactly does just a simple example)

class CustomProperty:
"""Serves as a mock property for a User object"""

def __init__(self, table, name, value):
self.table = table
self.name = name
self.value = value

#below is essentially the magic here
def __eq__(self, other):
return f"{self.table.__class__.__name__}.{self.name} == {other}"

class User:
"""Just a simple User class for example sake"""
def __init__(self, *args, **kwargs):
for k, v in kwargs.items():
setattr(self, k, CustomProperty(self, k, v))

#Here’s a basic example of what the `or_` method does.
def or_(*conditions):
return ' OR '.join(conditions)

user = User(name=str)

print(or_(user.name == 'bob', user.name == 'sally'))

This prints:

'User.name == bob OR User.name == sally'

Hopefully this helps break it down to what you were asking.

Edit

If you want to know where in the source code these methods can be found to trace out how it’s actually done by sqlalchemy refer to these links:

or_() - sqlalchemy.sql.expression.or_

__eq__ - sqlalchemy.sql.operators.ColumnOperators.eq

operator python parameter

The operator module is what you are looking for.
There you find functions that correspond to the usual operators.

e.g.

operator.lt
operator.le

Passing operators as functions to use with Pandas data frames

I'm all about @cᴏʟᴅsᴘᴇᴇᴅ's answer and @Zero's linked Q&A...

But here is an alternative with numexpr

import numexpr as ne

s[ne.evaluate('s {} {}'.format(ops[cfg['op']], cfg['threshold']))]

0 -0.308855
1 -0.031073
3 -0.547615
Name: A, dtype: float64

I reopened this question after having been closed as a dup of How to pass an operator to a python function?

The question and answers are great and I showed my appreciation with up votes.

Asking in the context of a pandas.Series opens it up to using answers that include numpy and numexpr. Whereas trying to answer the dup target with this answer would be pure nonsense.

Passing a comparison operator with a value into a function

Use the operator module:

def factor_test(factor1, factor2, criteria1, text, criteria2, op):
bool_mask1 = rnt2[factor1].str.contains(criteria1,na=False)
bool_mask2 = op(rnt2[factor2], criteria2)
test_name = rnt2[(bool_mask1) & (bool_mask2)]

Then call with different operators:

import operator

factor_test(factor1, factor2, criteria1, text, criteria2, operator.le) # <=
factor_test(factor1, factor2, criteria1, text, criteria2, operator.eq) # ==
# etc

How to pass multiple operators with value as an argument to the python method

You cannot pass condition in that form, that isn't valid Python syntax. But you can make simple lambda function and pass it as a parameter:

def myFunction(list1, condition) :
for value in list1:
if condition(value): # note we call here the lambda function
print(value, "out of range")
else :
print(value, "within range")

list1 =[1, 2, 3, 0, 5, 10]

myFunction(list1, lambda value: (value >= 9) | (value < 1))

Prints:

1 within range
2 within range
3 within range
0 out of range
5 within range
10 out of range

EDIT: If lambda function isn't enough, you can make standard function with def and pass it to the myFunction as lambda.

Or (as @Solonotix mentioned in the comments), any object with __call__ method).

Python Mathematical signs in function parameter?

You can not pass operator to the function, but however you may pass operator's functions defined in operator library. Hence, your function will be like:

>>> from operator import eq, add, sub
>>> def magic(left, op, right):
... return op(left, right)
...

Examples:

# To Add
>>> magic(3, add, 5)
8
# To Subtract
>>> magic(3, sub, 5)
-2
# To check equality
>>> magic(3, eq, 3)
True

Note: I am using function as magic instead of math because math is default python library and it is not good practice to use predefined keywords.



Related Topics



Leave a reply



Submit