Python: Is it bad form to raise exceptions within __init__?

Question:

Is it considered bad form to raise exceptions within __init__? If so, then what is the accepted method of throwing an error when certain class variables are initialized as None or of an incorrect type?

Asked By: user178884

||

Answers:

I should think it is the perfect case for the built-in ValueError exception.

Answered By: Teddy

The standard library says:

>>> f = file("notexisting.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'notexisting.txt'

Also I don’t really see any reason why it should be considered bad form.

Answered By: sth

Raising exceptions within __init__() is absolutely fine. There’s no other good way to indicate an error condition within an initializer, and there are many hundreds of examples in the standard library where initializing an object can raise an exception.

The error class to raise, of course, is up to you. ValueError is best if the initializer was passed an invalid parameter.

Answered By: John Millikin

I don’t see any reason that it should be bad form.

On the contrary, one of the things exceptions are known for doing well, as opposed to returning error codes, is that error codes usually can’t be returned by constructors. So at least in languages like C++, raising exceptions is the only way to signal errors.

Answered By: Edan Maor

I concur with all of the above.

There’s really no other way to signal that something went wrong in the initialisation of an object other than raising an exception.

In most programs classes where the state of a class is wholly dependant on the inputs to that class we might expect some kind of ValueError or TypeError to be raised.

Classes with side-effects (e.g. one which does networking or graphics) might raise an error in init if (for example) the network device is unavailable or the canvas object cannot be written to. This sounds sensible to me because often you want to know about failure conditions as soon as possible.

Answered By: Salim Fadhley

It’s true that the only proper way to indicate an error in a constructor is raising an exception. That is why in C++ and in other object-oriented languages that have been designed with exception safety in mind, the destructor is not called if an exception is thrown in the constructor of an object (meaning that the initialization of the object is incomplete). This is often not the case in scripting languages, such as Python. For example, the following code throws an AttributeError if socket.connect() fails:

class NetworkInterface:
    def __init__(self, address)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect(address)
        self.stream = self.socket.makefile()

    def __del__(self)
        self.stream.close()
        self.socket.close()

The reason is that the destructor of the incomplete object is called after the connection attempt has failed, before the stream attribute has been initialized. You shouldn’t avoid throwing exceptions from constructors, I’m just saying that it’s difficult to write fully exception safe code in Python. Some Python developers avoid using destructors altogether, but that’s a matter of another debate.

Answered By: Seppo Enarvi

Raising errors from init is unavoidable in some cases, but doing too much work in init is a bad style. You should consider making a factory or a pseudo-factory – a simple classmethod that returns setted up object.

Answered By: Ctrl-C
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.