noMAD
noMAD

Reputation: 7844

Create object with variable attributes in a cleaner way in python

Am new to python and I had to create an object only with certain attributes that are not None. Example:

if self.obj_one is None and self.obj_two is None:
    return MyObj(name=name)
elif self.obj_one is not None and self.obj_two is None:
    return MyObj(name=name, obj_one=self.obj_one)
elif self.obj_one is None and self.obj_two is not None:
    return MyObj(name=name, obj_two=self.obj_two)
else:
    return MyObj(name=name, obj_one=self.obj_one, obj_two=self.obj_two)

Coming from a Java land I know python is full of short hand so wanted to know if there is a cleaner way for writing the above? Of course my actual object has plenty more attributes. I tried searching but couldn't find anything helpful so am in doubt if its possible or not cause this doesn't scale if there are more than 2 variable attributes.

Upvotes: 2

Views: 46

Answers (1)

Andrea Corbellini
Andrea Corbellini

Reputation: 17771

One way could be using the double-star operator, like this:

kwargs = {'name': name}

if self.obj_one is not None:
    kwargs['obj_one'] = self.obj_one
if self.obj_two is not None:
    kwargs['obj_two'] = self.obj_two

return MyObj(**kwargs)

In plain words: you construct a dictionary with your keyword arguments, and then pass that dictionary preceded by ** to the callable.

However, None is often (not always) used as a default value for optional arguments. Probably this will work too:

return MyObj(name=name, obj_one=self.obj_one, obj_two=self.obj_two)

without any if or that sort of stuff.

Upvotes: 5

Related Questions