在 SQLAlchemy 中,我似乎应该将表达式传递给 filter()
在某些情况下.当我尝试自己实现这样的事情时,我最终得到:
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?
如果你把op"变成一个函数,你可以实现你的例子:
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
这比传递字符串更具 Pythonic.这就是 sort()
等函数的工作原理.
This is more Pythonic than passing a string. It's how functions like sort()
work.
那些带有 filter()
的 SQLAlchemy 示例令人费解.我不知道有关 SQLAlchemy 的内部结构,但我猜在像 query.filter(User.name == 'ed')
这样的例子中发生了什么是 User.name
是特定于 SQLAlchemy 的类型,具有 __eq()
函数的奇怪实现,它为 filter()
函数生成 SQL 而不是进行比较.即:他们制作了特殊的类,可让您键入发出 SQL 代码的 Python 表达式.这是一种不寻常的技术,我会避免使用这种技术,除非构建像 ORM 这样桥接两种语言的东西.
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.