Reputation: 393
This is my current implementation:
def update_obj(obj_id, field1=None, field2=None):
obj = ... # some code to get object by obj_id
if field1 is not None:
obj.field1 = field1
if field2 is not None:
obj.field2 = field2
update_obj(1, field1='new value')
update_obj(2, field2='new value')
update_obj(3, field1='new value', field2='another new value')
I try do the evaluation in one line, like:
obj.field1 = field1 if field1 is not None else ob.field1
However, the obj.field1 = obj.field1
is quite redundant and obj.field1 = field1 if field1 is not None
is not a valid statement.
Any suggestion to make it simpler and cleaner? I'm using python 2.7.
Upvotes: 0
Views: 149
Reputation: 35998
If it's code duplication that bothers you, you may use reflection, e.g.:
obj.__dict__.update(n,v for n,v in locals() if n in 'field1','field2' and v is not None)
Upvotes: 1
Reputation: 2178
I'd use or
.
obj.field1 = field1 or or obj.field1
It doesn't remove the redundancy, but it is a little more concise.
Upvotes: 0