Help cleaning up some code

Gerard Flanagan grflanagan at gmail.com
Sat Mar 7 09:41:22 CET 2009


odeits wrote:
> I am looking to clean up this code... any help is much appreciated.
> Note: It works just fine, I just think it could be done cleaner.
> 
> The result is a stack of dictionaries. the query returns up to
> STACK_SIZE ads for a user. The check which i think is very ugly is
> putting another contraint saying that all of the ni have to be the
> same.
> 
> stack = []
> rows = self.con.execute(adquerystring,(user,STACK_SIZE)).fetchall()
> for row in  rows:
>             ad = dict()
>             ad['ni'] = row['ni']
>             ad['adid'] = row['adid']
>             ad['rundateid'] = row['rundateid']
>             ad['rundate'] = row['rundate']
>             if row['city'] is None:
>                 ad['city'] = 'None'
>             else:
>                 ad['city'] = row['city']
>             if row['state'] is None:
>                 ad['state'] = 'None'
>             else:
>                 ad['state'] = row['state']
>             ad['status'] = row['status']
>             try:
>                 if stack[0]['ni'] != ad['ni']:
>                     break;
>             except IndexError:
>                 pass
>             stack.append(ad)
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Random ideas:

def fetchsomedata(self, user):
     query = 'some query'
     return list(self._fetch(query, user, STACKSIZE))

def _fetchsomedata(self, query, *params):
     keys = 'adid rundateid rundate status'.split()
     specialkeys = 'city state'.split()
     nikey = 'ni'
     ni = None
     for row in self.con.execute(query, params).fetchall():
         nival = row[nikey]
         if ni != nival:
             break
         if ni is None:
             ni = nival
         data = {nikey: nival}
         for k in keys:
             data[k] = row[k]
         for k in specialkeys:
             data[k] = 'None' if row[k] is None else row[k]
         yield data








More information about the Python-list mailing list