解决python中的lambda限制

时间:2018-10-18 20:31:00

标签: 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 );

我想知道是否有可能

谢谢。

1 个答案:

答案 0 :(得分:0)

如果您要编写的函数足够重要,可以包含多个语句,那么将其定义为适当的函数就足够重要。

您可以这样定义它:

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