Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try and create on exception in Python

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?

like image 899
Damián Castro Avatar asked Jan 22 '26 08:01

Damián Castro


1 Answers

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.

like image 91
John Gordon Avatar answered Jan 23 '26 23:01

John Gordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!