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

PythonException

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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.

Solution 4 - Python

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.

Solution 5 - Python

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

Solution 6 - Python

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.

Solution 7 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser178884View Question on Stackoverflow
Solution 1 - PythonJohn MillikinView Answer on Stackoverflow
Solution 2 - PythonSeppo EnarviView Answer on Stackoverflow
Solution 3 - PythonEdan MaorView Answer on Stackoverflow
Solution 4 - PythonsthView Answer on Stackoverflow
Solution 5 - PythonTeddyView Answer on Stackoverflow
Solution 6 - PythonSalim FadhleyView Answer on Stackoverflow
Solution 7 - PythonCtrl-CView Answer on Stackoverflow