Python __init__ returns failure to create

First, I know that the class __init__() function in Python cannot return a value, so unfortunately this option is not available.

Due to the structure of my code, it makes sense to have data statements (and tips for the user to give information) inside the __init__ class function. However, this means that the creation of the object may fail, and I would like it to be able to gracefully recover from it.

I was wondering what the best way to continue this. I decided to set the global boolean value as the flag of the "correct design", but I would prefer not to.

Any other ideas (besides restructuring, such statements can occur outside of initialization, and values ​​are passed as arguments)? I am basically looking for a way to return 0 on success and return -1 on failure during initialization. (Like most C system calls)

+7
source share
2 answers

You can throw an exception if either assertio fail, or - if you really do not want or cannot work with exceptions, you can write the __new__ method in your classes - in Python __init__ technically the "initializer" of the method - and it must fill in its attributes and acquire some resources and other objects that you will need throughout the life cycle. However, Python does define a real constructor, __new__ , which is called before __init__ - and in contrast, __new__ does return a value: the newly created (uninitialized) instance itself.

So, you can put your checks inside __new__ and simply return None - something fails - otherwise return the call result to the __new__ superclass __new__ (you cannot actually allocate memory for an object in pure Python, so in the end you need to call the constructor written in native code in a superclass - usually this is object.__new__ in the base of your class hierarchy.

NB . In Python 2, you should have object as the base class for your hierarchy - otherwise, not only __new__ will not be called, like many functions added later in Python, objects simply do not work. In short, class MyClass(object): never class MyClass: - if you are not in Python3.

+11
source

Have you considered raising an exception? This is the usual way to report a failure.

0
source

All Articles