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?
As far as I can tell, simply using a different name for the message attribute avoids the conflict with the base class, and thus stops the deprecation warning:
Seems like a hack to me.
Maybe someone can explain why the warning is issued even when the subclass defines a message attribute explicitly. If the base class no longer has this attribute, there shouldn't be a problem.
This is your class in Python2.6 style. The new exception takes an arbitrary number of arguments.
The advice to use str(myexception) leads to unicode problems in python 2.7, e.g.:
:(
works as expected, and is preferred in cases where some of the content of the error string includes user input
Continuing on from geekQ's answer, the preferred code replacement depends on what you need to do:
Yes, it's deprecated in Python 2.6 because it's going away in Python 3.0
BaseException class does not provide a way to store error message anymore. You'll have to implement it yourself. You can do this with a subclass that uses a property for storing the message.
Hope this helps
Solution - almost no coding needed
Just inherit your exception class from
Exception
and 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_message
as suggested by others.