Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

exception - BaseException.message deprecated in Python 2.6

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...