简体   繁体   English

解决python中的lambda限制

[英]Working around lambda limitation in python

To get more familiar with Python , I'm trying to write a number of sql related functions. 为了更熟悉Python,我正在尝试编写许多与sql相关的函数。 One of them is supposed to execute a query and convert result to named tuple. 其中之一应该执行查询并将结果转换为命名元组。 Relevant piece of code. 相关代码段。

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);

The code works , and I can pass callback using nested function : 该代码有效,并且我可以使用嵌套函数传递回调:

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);

or with multiple lambdas , eg 或具有多个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);

However, I cannot figure out how wrap the latter in series of wrapped lambda. 但是,我不知道如何将后者包装成一系列包装好的lambda。 I want something like : 我想要类似的东西:

     # 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 );

I wonder if that's possible at all 我想知道是否有可能

Thanks. 谢谢。

If the function you're writing is important enough to have multiple statements, it's important enough to be defined as a proper function. 如果您正在编写的函数足够重要以具有多个语句,那么将其定义为适当的函数也足够重要。

You define it like this: 您可以这样定义它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM