Help cleaning up some code
andrew at acooke.org
Sat Mar 7 06:43:12 CET 2009
> 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
> 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'
> ad['city'] = row['city']
> if row['state'] is None:
> ad['state'] = 'None'
> ad['state'] = row['state']
> ad['status'] = row['status']
> if stack['ni'] != ad['ni']:
> except IndexError:
NI = 'ni'
def copy(src, dst, name, quote_none=False):
value = src[name]
dst[name] = 'None' if quote_none and value is None else value
stack = 
for row in self.con.execute(adquerystring,(user,STACK_SIZE)).fetchall():
ad = dict()
for name in (NI, 'adid', 'rundateid', 'rundate', 'status'):
copy(row, ad, name)
for name in ('city', 'state'):
copy(row, ad, name, quote_none=True)
if stack and stack[NI] != ad[NI]:
but couldn't you change the query so that it only returns a single 'ni'?
also, do you really want to break, or just skip the append? maybe you want:
if not stack or stack['ni'] == ad['ni']:
or perhaps the 'ni' are sorted (in which case what you are doing makes
More information about the Python-list