lundi 11 septembre 2017

How to avoid code duplication in async loop?

I have the following code that has duplicated functionality.

async def execute_select_query(self, query: str, keys: tuple) -> List[dict]:
    async with self.pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(query)
            return [dict(zip(keys, row)) async for row in cur]

async def execute_insert_query(self, query: str):
    async with self.pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(query)

How to avoid code duplication?

I have an idea to create a separate method like:

async def execute(self, query: str)
  async with self.pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(query)

but I don't know how to use it in execute_select_query

Aucun commentaire:

Enregistrer un commentaire