Passing expressions to functions(将表达式传递给函数)
问题描述
在 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.
这篇关于将表达式传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将表达式传递给函数
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
