'Python: Comparison in function argument

I am currently working on the following problem:

I want to write a function, that accepts comparisons as arguments - but want to prevent, that these comparisons are evaluated during runtime (leading to potentially unexpected results).

To be more precise, I have the following challenge (first, original one in pySpark, then similar, more general one):

def test_func(*comparisons):
    for comparison in comparison:
        left_hand = comparison[0]
        comparison = comparison[1]
        right_hand = comparison[2]

Example 1:

test_func(F.col('a') == F.col('b'))

left_hand -> F.col('a')
right_hand -> F.col('b')
comparison -> ==

Example 2:

test_func(1 <=> 2)

left_hand -> 1
right_hand -> 2
comparison -> <=>

Right now, the equation/parameter is evaluated before it reaches the function - i.e., I have problems splitting the equation into it individual parts.

Is this even possible to like this?



Solution 1:[1]

The python operator module stores operators as functions

from operator import *
def test_func(*comparison):
    left_hand = comparison[0]
    comparison = comparison[1]
    right_hand = comparison[2]

test_func(F.col('a'), eq, F.col('b'))

The variables would be (remember they would still be local to test_func):

left_hand = F.col('a')
comparison = eq            -> operator.eq
right_hand = F.col('b')

Solution 2:[2]

As a quick proof of concept:

>>> import operator
>>> class Col:
...    def __init__(self, col):
...        self.col = col
...        
...    def __eq__(self, other):
...        return self, operator.eq, other
...
>>> Col('a') == Col('b')
(<__main__.Col object at 0x11134d5b0>, <built-in function eq>, <__main__.Col object at 0x11147cbe0>)
>>> lh, comp, rh = Col('a') == Col('b')
>>> comp(lh.col, rh.col)
False

You'll need to overload all special methods for all operators you want to support, and return the equivalent operator function (or whatever you want, perhaps '==', or a custom object).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ukulele
Solution 2 deceze