In SQLAlchemy, it appears I'm supposed to pass an expression to filter()
in certain cases. When I try to implement something like this myself, I end up with:
>>> def someFunc(value): ... print(value) >>> someFunc(5 == 5) True
How do I get the values passed to ==
from inside the function?
I'm trying to achieve something like this
>>> def magic(left, op, right): ... print(left + " " + op + " " + right) >>> magic(5 == 5) 5 == 5
What about if one of the parameters was an object?
Short answer: You can't. The result of the expression evaluation is passed to the function rather than the expression itself.
Thus an expression represents a function whose inputs are the values assigned to the free variables and whose output is the resulting value of the expression. For example, the expression. evaluated for x = 10, y = 5, will give 2; but it is undefined for y = 0.
Functions are data, and therefore can be passed around just like other values. This means a function can be passed to another function as an argument. This allows the function being called to use the function argument to carry out its action.
When the function is called, the parameter passed to it must be a variable, and that variable's address is passed to the function. Any time the function's body uses the parameter, it uses the variable at the address that was passed.
You can achieve your example if you make "op" a function:
>>> def magic(left, op, right): ... return op(left, right) ... >>> magic(5, (lambda a, b: a == b), 5) True >>> magic(5, (lambda a, b: a == b), 4) False
This is more Pythonic than passing a string. It's how functions like sort()
work.
Those SQLAlchemy examples with filter()
are puzzling. I don't know the internals about SQLAlchemy, but I'm guessing in an example like query.filter(User.name == 'ed')
what's going on is that User.name
is a SQLAlchemy-specific type, with an odd implementation of the __eq()
function that generates SQL for the filter()
function instead of doing a comparison. Ie: they've made special classes that let you type Python expressions that emit SQL code. It's an unusual technique, one I'd avoid unless building something that's bridging two languages like an ORM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With