【问题标题】:How do I raise DeprecationWarnings in Python 2.7?如何在 Python 2.7 中引发 DeprecationWarnings?
【发布时间】:2015-03-31 21:01:46
【问题描述】:

我试图将一个函数标记为已弃用,以便调用它的脚本运行到正常完成,但被 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 Warnings 应该允许代码运行,但这个代码示例实际上在调用函数时会停止。当我从函数体中删除“raise”时,代码会运行,但 PyCharm 不会将函数调用标记为已弃用。

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

【问题讨论】:

    标签: python-2.7 pycharm


    【解决方案1】:

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

    改为使用warnings.warn:

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

    【讨论】:

    • 谢谢!正是我想要的。脚本现在运行,但 PyCharm 删除了函数调用。我被从异常继承的警告误导了:docs.python.org/2/library/exceptions.html#exception-hierarchy
    • @Beachcomber:PyCharm 删除了函数调用,因为您将其标记为已弃用。该功能仍然有效,但它已被明显标记,因此您知道将代码更改为不使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 2015-11-15
    • 2014-08-20
    • 1970-01-01
    • 2019-08-24
    • 2020-02-03
    • 2017-11-04
    相关资源
    最近更新 更多