Don't create object when if condition is not met in __init__()

Viewed 5219

I have a class that maps a database object

class MyObj:
    def __init__(self):
        ...SQL request with id as key...
        if len(rows) == 1:
            ...maps columns as my_obj attributes...
            self.exists = True
        else:
            self.exists = False

With such design, an object is created each time, and we check if it is present in database with .exists attribute.

my_obj = MyObj(id=15)
if my_obj.exists:
    ...do stuff...

It works.

But I suspect there is a cleaner way to init, and we would just have to check like that:

 my_obj = MyObj(id=15)
 if my_obj:
     ...do stuff...
1 Answers
Related