comte
comte

Reputation: 3344

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

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...

Upvotes: 9

Views: 6879

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121972

You can't do this in __init__, because that method is run after the new instance is created.

You can do it with object.__new__() however, this is run to create the instance in the first place. Because it is normally supposed to return that new instance, you could also choose to return something else (like None).

You could use it like this:

class MyObj:
    def __new__(cls, id):
        # ...SQL request with id as key...
        if not rows:
            # no rows, so no data. Return `None`.
            return None

        # create a new instance and set attributes on it
        instance = super().__new__(cls)  # empty instance
        instance.rows = ...
        return instance

Upvotes: 9

Related Questions