简体   繁体   中英

Working around lambda limitation in python

To get more familiar with Python , I'm trying to write a number of sql related functions. 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

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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