Terrence Brannon
Terrence Brannon

Reputation: 4968

How can I make this code more DRY

From web2py example 33 we see:

db.purchase.insert(buyer_id=form.vars.buyer_id,  
   product_id=form.vars.product_id, 
   quantity=form.vars.quantity)

but I think there should be some way to make this less repetitive. perhaps this?

db.purchase.insert(**dict( [k = getattr(form.vars, k) for k in "buyer_id product_id quantity".split()]))

Upvotes: 0

Views: 97

Answers (3)

Joran Beasley
Joran Beasley

Reputation: 113978

if those 3 things are all there is you could do

db.purchase.insert(**form.vars)

otherwise I think that the original code is plenty dry

but i guess you could do

to_insert = {"product_id":form.vars.product_id,"quantity":form.vars.quantity,"buyer_id":form.vars.buyer_id}
db.purchase.insert(**to_insert) 

which is similar to your second example but is more readable and simple (some of the tenets of python)

Upvotes: 0

Jacob Mattison
Jacob Mattison

Reputation: 51052

For me, DRY means 1) not repeating actual code, and 2) (and more important) not repeating information; i.e. there should be one place that each item of information exists.

In this instance, you're really just repeating a pattern, and I think that's fine. The second example is much harder to read; why complicate it just to save a few characters?

Upvotes: 6

Mark Byers
Mark Byers

Reputation: 838186

You could avoid repeating form.vars:

vars = form.vars
db.purchase.insert(
    buyer_id=vars.buyer_id,  
    product_id=vars.product_id, 
    quantity=vars.quantity)

There is still some repetition, but I think it's better to leave it with some repetition rather than making your code hard to read.

Upvotes: 2

Related Questions