user3778914
user3778914

Reputation: 393

Elegant way to assign value only when it is not None

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

Answers (2)

ivan_pozdeev
ivan_pozdeev

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

jlb83
jlb83

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

Related Questions