Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...
like image 598
comte Avatar asked May 23 '17 16:05

comte


People also ask

How do you not create an object in Python?

Simply put the functions in a separate module (. py file) and put your variables in the module scope (e.g. global variables) - that's the pythonic way to do what you want if you do not need thread safety.

Is __ init __ compulsory in Python?

But in Python, it is not compulsory that the parent class constructor will always be called first. The order in which the __init__ method is called for a parent or a child class can be modified.

What is the point of __ init __?

The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

What is __ new __ in Python?

__new__ is static class method, while __init__ is instance method. __new__ has to create the instance first, so __init__ can initialize it. Note that __init__ takes self as parameter. Until you create instance there is no self . Now, I gather, that you're trying to implement singleton pattern in Python.


1 Answers

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
like image 171
Martijn Pieters Avatar answered Sep 22 '22 10:09

Martijn Pieters