python - 解决 python 中的 lambda 限制

标签 python python-3.x lambda psycopg2

为了更熟悉Python,我正在尝试编写一些与sql相关的函数。其中之一应该执行查询并将结果转换为命名元组。相关代码片段。

from collections import namedtuple, Iterable
import psycopg2.extras
import psycopg2

def tuple_to_named_tuple(tuple, cursor_description) -> list:
    rdef = namedtuple('row', ' '.join([x[0] for x in cursor_description]))
    return rdef._make(tuple);

def run_query(connection_string, callback_function):
    with  psycopg2.connect(connection_string) as conn:
        with conn.cursor() as cur:
            return callback_function(cur);

代码有效,我可以使用嵌套函数传递回调:

def test_param(value):
    def nested_function(cur):
        cur.execute("SELECT val from table1 where id =%", (value,));
        return tuple_to_named_tuple(cur.fetchone(), cur.description);    
    val = run_query(CONNECTION_STRING, nested_function);
    print(val);

或者使用多个 lambda,例如

def test_param(value):
    cb = lambda cur: (cur.execute("SELECT val from table1 where id =%", (value,)), cur);
    cb1 = lambda ignore, cur: tuple_to_named_tuple(cur.fetchone(), cur.description);
    cb3 = lambda c1: cb1(*cb(c1));
    val = run_query(CONNECTION_STRING, cb3);
    print(val);

但是,我无法弄清楚如何将后者包装在一系列包装的 lambda 中。我想要类似的东西:

     # not working code
 lambda_callback = lambda cur : 
          lambda ignore, cur : 
   *(cur.execute("SELECT val from table1 where id =%", (value,))[0], 
   *(cur.execute("SELECT val from table1 where id =%", (value,))[1]; 
val = run_query(CONNECTION_STRING, lambdas_callback );

我想知道这是否可能

谢谢。

最佳答案

如果您正在编写的函数足够重要,需要包含多个语句,那么它也足够重要,可以定义为正确的函数。

你这样定义它:

def my_important_multistatement_lambda_func(*args, **kwargs):
    # TODO

关于python - 解决 python 中的 lambda 限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52882086/

相关文章:

python - 可调用实例参数的表示法是什么?

ruby-on-rails - 具有多个参数的 Rails 作用域

C++ : What are the purpose of captures in lambda expressions?

python - 按值对字典进行排序,然后将排序后的值附加到文本文件中

python - 多幅图像的边缘检测

python-3.x - 机器学习预处理错误

http - 这些 python Web 服务器请求之间有什么区别?

java - 为什么我不能在 Java 8 lambda 表达式中引发异常?

python - F.monotonicly_increasing_id() 返回长随机数

python - 在脚本中使用 Python 中的 nose 时覆盖现有配置