Help cleaning up some code

Scott David Daniels Scott.Daniels at Acm.Org
Sat Mar 7 22:07:07 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.

Well, the obvious way to get your constraint is by changing your SQL,
but if you are going to do it by fetching rows, try:

     FIELDS = 'ni adid rundateid rundate city state status'.split()
     ni = UNSET = object() # use None unless None might be the value
     stack = []
     rows = self.con.execute(adquerystring, (user,STACK_SIZE)).fetchall()
     for row in rows:
         ad = dict()
         for field in FIELDS:
             ad[field] = row[field]
         for field in 'city', 'state':
             if ad[field] is None:
                 ad[field] = 'None'
         if ni != ad['ni']:
             if ni is UNSET:
                 ni = ad['ni']

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list