Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass in logical operators (and partial expressions) into a function argument Python

In SQLAlchemy, it is possible to do something like this:

mytable.query.filter(mytable.some_col < 5).all()

How can I implement something similar? I want developer users to be able to pass in logical operations to a function. Here's an example:

class row_obj:
    def __init__(self, val1, val2, val3, val4):
        self.val1 = val1
        self.val2 = val2
        self.val3 = val3
        self.val4 = val4
    def __repr__(self):
        return str(self.val1)+","+str(self.val2)+","+str(self.val3)+","+str(self.val4)

class table_obj:
    """ takes a list of row_objs """
    def __init__(self, rows):
        self.rows = rows #rows is a list of row_obj 
    def __repr__(self):
        return "\n".join([str(row) for row in self.rows])
    def filter(self, condition):
        # I would like to return all rows which meet the condition here
        return table_obj([row for row in self.rows if condition])

a = table_obj([ row_obj(1,2,3,4),
      row_obj(5,6,7,8),
      row_obj(2,4,6,8),
      row_obj(5,2,7,4)])

print a.filter(row_obj.val3 == 7)
#should return 
#5,6,7,8
#5,2,7,4
like image 392
mgoldwasser Avatar asked Jan 18 '26 02:01

mgoldwasser


1 Answers

As you mentioned, SQLAlchemy allows expressions like:

mytable.query.filter(mytable.some_col < 5).all()

This is possible because mytable.some_col implements magic methods for each logical operator which returns some other object (in this case __lt__). So the operator is not really passed in. In my application, which defines a User object, this can be seen via:

>>> User.first_name == 'John'
<sqlalchemy.sql.elements.BinaryExpression object at 0x10f0991d0>

You could do the same to achieve the same effect.

like image 111
Ceasar Bautista Avatar answered Jan 19 '26 16:01

Ceasar Bautista



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!