Search code examples
pythonfunctionargumentsoperatorscomparison-operators

Passing a comparison operator with a value into a function


I am defining a function where one parameter should be a comparison operator.

I have tried different versions of transforming commands such as float and input

Code I am trying:

def factor_test(factor1, factor2, criteria1, text, criteria2):
    bool_mask1 = rnt2[factor1].str.contains(criteria1,na=False)
    bool_mask2 = rnt2[factor2] criteria2
    # Returns values that are TRUE i.e. an error, not an Boolean dataframe but actual values
    test_name = rnt2[(bool_mask1) & (bool_mask2)] 

criteria2 should be > 0.75:

bool_mask2 = rnt2[factor2] > 0.75

Preferred would be one parameter where I can put in both the > and 0.75, the function should be used about 15 times, with !=, == and <.


Solution

  • 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