Help cleaning up some code
odeits
odeits at gmail.com
Sun Mar 8 01:58:22 EST 2009
On Mar 7, 1:07 pm, Scott David Daniels <Scott.Dani... at Acm.Org> wrote:
> 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']
> else:
> break
> stack.append(ad)
>
> --Scott David Daniels
> Scott.Dani... at Acm.Org
Taking from several suggestions this is what i have come up with for
now:
for row in ifilter(lambda r: r['ni'] == rows[0]['ni'],rows):
ad = dict()
keys = row.keys() # if python 2.6
keys =
['ni','adid','rundateid','rundate','city','state','status'] # if
python 2.5
for index in row.keys():
if row[index] is None:
ad[index] = 'None'
else:
ad[index] = row[index]
stack.append(ad)
print row
the test to see if the ad is valid is placed in the ifilter so that I
dont build the dictionary unnecessarily. and the None special case is
fairly simple to read now. The None case would even be irrelevant if i
could get the damn xmlrpc to allow null. sigh. anyhow. thanks for all
of your input, it is definitely better than it was ;)
More information about the Python-list
mailing list