如何在Python 2.7中引发DeprecationWarnings?

16

我希望将一个函数标记为已弃用,以便调用该函数的脚本可以正常完成运行,但会被 PyCharm 的静态代码检查所捕获。 (关于这个弃用警告还有一些其他问题,但我认为它们早于 Python 2.6,那时据信引入了基于类的异常。)

以下是我的实现:

class Deprecated(DeprecationWarning):
    pass

def save_plot_and_insert(filename, worksheet, row, col):
    """
    Deprecated. Docstring ...<snip>
    """

    raise Deprecated()

    # Active lines of
    # the function here
    # ...

我的理解是:Deprecated警告应该允许代码运行,但是这个代码示例实际上在调用函数时停止了。当我从函数体中删除“raise”时,代码可以运行,但是PyCharm不会将函数调用标记为已弃用。

Pythonic(2.7.x)中将函数标记为已弃用的方法是什么?

1个回答

29

不应该 raise DeprecationWarning(或其子类),因为这样你仍然会抛出实际的异常。

相反,使用 warnings.warn

import warnings
warnings.warn("deprecated", DeprecationWarning)

谢谢!正是我想要的。脚本现在可以运行了,但是PyCharm划掉了函数调用。我被继承自异常的警告所误导:https://docs.python.org/2/library/exceptions.html#exception-hierarchy - Beachcomber
@Beachcomber:PyCharm标记该函数调用已过时,因此它会被划掉。该函数仍然可以使用,但是它被明确标记为过时,以便您知道要更改代码以不使用它。 - A. R. Diederich

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接