2

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.