Python 2.6中BaseException.message已被弃用

185 投票
8 回答
95089 浏览
提问于 2025-04-15 13:34

我在使用下面这个自己定义的异常时,收到了一个警告,提示在Python 2.6中BaseException.message已经不推荐使用了:

class MyException(Exception):

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

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

这是那个警告:

DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message

这有什么问题呢?我需要做什么改变才能消除这个不推荐使用的警告呢?

8 个回答

10

如何重现警告

让我来解释一下这个问题,因为用问题中的示例代码无法重现这个警告。如果你在Python 2.6和2.7中开启了警告(通过-W标志PYTHONWARNINGS环境变量,或者警告模块),就可以重现这个警告:

>>> error = Exception('foobarbaz')
>>> error.message
__main__:1: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
'foobarbaz'

停止使用 .message

我更喜欢使用 repr(error),这个方法会返回一个字符串,里面包含错误类型的名称、消息的表示(如果有的话),以及其他参数的表示。

>>> repr(error)
"Exception('foobarbaz',)"

在仍然使用 .message 的情况下消除警告

要消除 DeprecationWarning 警告,你可以像Python设计者所建议的那样,创建一个内置异常的子类:

class MyException(Exception):

    def __init__(self, message, *args):
        self.message = message
        # delegate the rest of initialization to parent
        super(MyException, self).__init__(message, *args)

>>> myexception = MyException('my message')
>>> myexception.message
'my message'
>>> str(myexception)
'my message'
>>> repr(myexception)
"MyException('my message',)"

仅获取 .message 属性,而不使用 error.message

如果你知道异常有一个参数,也就是消息,并且你只想要这个消息,最好避免使用消息属性,直接获取错误的 str。比如对于一个子类化的 Exception

class MyException(Exception):
    '''demo straight subclass'''

使用示例:

>>> myexception = MyException('my message')
>>> str(myexception)
'my message'

另请参见这个回答:

现代Python中声明自定义异常的正确方式是什么?

25

是的,在Python 2.6中这个功能已经被淘汰,因为在Python 3.0中将不再使用。

BaseException类现在不再提供存储错误信息的方法了。你需要自己来实现这个功能。你可以通过创建一个子类,使用一个属性来存储错误信息。

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

希望这对你有帮助

160

解决方案 - 几乎不需要编码

只需让你的异常类继承自 Exception,然后把消息作为第一个参数传给构造函数就可以了。

示例:

class MyException(Exception):
    """My documentation"""

try:
    raise MyException('my detailed description')
except MyException as my:
    print my # outputs 'my detailed description'

你可以用 str(my) 或者(不太优雅的方式)用 my.args[0] 来获取自定义的消息。

背景

在较新的 Python 版本中(从 2.6 开始),我们应该让自定义的异常类继承自 Exception,而 Exception 又是从 BaseException 继承来的。这个背景在 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____repr__ 已经以有意义的方式实现了,特别是当只有一个参数(可以用作消息)时。

你不需要重复实现 __str____init__,也不需要像其他人建议的那样创建 _get_message

撰写回答