I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:
class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
This is the warning:
DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
What’s wrong with this? What do I have to change to get rid of the deprecation warning?
Solution – almost no coding needed
Just inherit your exception class from
Exceptionand pass the message as the first parameter to the constructorExample:
You can use
str(my)or (less elegant)my.args[0]to access the custom message.Background
In the newer versions of Python (from 2.6) we are supposed to inherit our custom exception classes from Exception which (starting from Python 2.5) inherits from BaseException. The background is described in detail in PEP 352.
__str__and__repr__are already implemented in a meaningful way,especially for the case of only one arg (that can be used as message).
You do not need to repeat
__str__or__init__implementation or create_get_messageas suggested by others.