In a Python class, what type of error should I raise from an instance method when some of the other attributes of the class must be changed before running that method?
I'm coming from a C# background where I would use InvalidOperationException
, "the exception that is thrown when a method call is invalid for the object's current state", but I couldn't find an equivalent built-in exception in Python.
I've been raising ValueError
("raised when a built-in operation or function receives an argument that has the right type but an inappropriate value") when the problem is with the function parameters. I suppose this is technically an invalid value for the self
parameter; is that the right way to treat it? For example, is this idiomatic: raise ValueError("self.foo must be set before running self.bar()")
?