Skip to content Skip to sidebar Skip to footer

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 m

Solution 1:

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

Post a Comment for "Don't Create Object When If Condition Is Not Met In __init__()"