BaseException.message deprecated in Python 2.6 BaseException.message deprecated in Python 2.6 python python

BaseException.message deprecated in Python 2.6


Solution - almost no coding needed

Just inherit your exception class from Exception and pass the message as the first parameter to the constructor

Example:

class MyException(Exception):    """My documentation"""try:    raise MyException('my detailed description')except MyException as my:    print my # outputs 'my detailed description'

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.

class BaseException(object):    """Superclass representing the base of the exception hierarchy.    Provides an 'args' attribute that contains all arguments passed    to the constructor.  Suggested practice, though, is that only a    single string argument be passed to the constructor."""

__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.


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.

class MyException(Exception):    def _get_message(self):         return self._message    def _set_message(self, message):         self._message = message    message = property(_get_message, _set_message)

Hope this helps


class MyException(Exception):    def __str__(self):        return repr(self.args[0])e = MyException('asdf')print e

This is your class in Python2.6 style. The new exception takes an arbitrary number of arguments.