views:

4038

answers:

4

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?

+9  A: 

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

Sahasranaman MS
This helped, thanks. Now to vent frustration: ARGH! :)
romkyns
How would you initialize the message during the raise?His code showed the message being set by calling MyException("some message")
eric.frederich
The methods in my example are only for implementing the message property. How the property is used is upto the coder. In this case OP uses the __init__ and __str__ methods that he has posted in his code.
Sahasranaman MS
+4  A: 
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.

maksymko
The old Exception class also takes any number of arguments. You can entirely avoid the message property like what you're doing, but if that would break your existing code, you can solve the problem by implementing your own message property.
Sahasranaman MS
A: 

It is unpythonic and useless to create properties that do nothing except getting and setting the value, unchecked and unchanged. The whole point of properties is to allow one to use public attributes freely, until such time as a getter or a setter is actually needed. Then you turn the public attribute into a property, without breaking any client code.

Luciano Ramalho
A: 

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:

class MyException(Exception):

def __init__(self, message):
    self.msg = message

def __str__(self):
    return repr(self.msg)

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.

Hollister