如何在 Python 2.7 中引发 DeprecationWarnings?

How do I raise DeprecationWarnings in Python 2.7?

我试图将一个函数标记为已弃用,以便调用它的脚本 运行 正常完成,但被 PyCharm 的静态代码检查捕获。 (关于此弃用警告还有一些其他问题,但我认为它们早于 Python 2.6,当时我相信引入了基于 class 的异常。)

这是我的:

class Deprecated(DeprecationWarning):
    pass

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

    raise Deprecated()

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

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

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

您不应该 raise DeprecationWarning(或子类),因为那样您仍然会引发实际异常。

改为使用warnings.warn:

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