Python: Is it bad form to raise exceptions within __init__?
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.
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.
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.