Reputation: 337
Python developers say that it's easier to ask for forgiveness than permission. Every time I can I follow that idea in my scripts. However I've arrived to situations where I don't know how to do that properly.
Let's say that you have a database of objects and you need to do stuff to those objects. When getting objects from the database it may happen that the object does not exist, so I decide to create it right there. Suppose further that the method for creating objects in database does not return the created object. The problem I have is that I'm repeating the code for getting the object:
try:
obj = get_obj(name="foo")
except DoesNotExists:
create_obj(name="foo")
obj = get_obj(name="foo")
do_stuff(obj)
Is there a way as to avoid the duplication of code?
Upvotes: 3
Views: 82
Reputation: 33335
Instead of calling get_obj() directly, create a helper function named get_or_create_obj().
This function returns the specified object if it already exists, otherwise it creates it and then returns it.
If you care whether or not the object was found or created, the function can return a tuple of (created_flag, object).
Your get_or_create_obj() still has code duplication, but only in the one spot.
Upvotes: 2