前言
在python中,如果你有函数或者类当下没有作用,或者即将废弃,但是你又不想删除,那么你可以标记为deprecated。其实我更想做的是什么?能够让我标记的函数或者类在其它地方使用的时候,能有直观的提示。用Idea做java开发的童鞋肯定很清楚,java代码中的类或者函数只要标记了@Deprecated注解,在所有使用它的地方都会有删除线很直观的标记出来。
那么,PyCharm或者Idea使用Python插件是否也有对Python进行deprecated检测并提示的能力呢?
有!
IDE配置
PyCharm和Idea非常的智能,能识别Python的函数或类是否被标记为deprecated,并展示删除线。
preferences->Editor-inspections
,搜索框中输入Deprecated,在Python那类中看是否有勾选住,默认应该是勾选的。
咱们看描述:
This inspection highlights usages of Python functions, classes or methods which are marked as deprecated (which raise a DeprecationWarning or a PendingDeprecationWarning).
意思是说:检查python的函数、类、或者类函数是否标记了deprecated(抛出DeprecationWarning或者PendingDeprecationWarning警告),如果标记了会高亮(实际是删除线)。
标记Deprecated示例
import warnings
def some_old_function(x, y):
# 这行告警代码被识别到
warnings.warn("some_old_function is deprecated", DeprecationWarning)
return x + y
some_old_function(12, 34)
关键是warnings.warn("some_old_function is deprecated", DeprecationWarning)
这行代码被PyCharm识别到了。
注意,上面只是让IDE能达到识别废弃并使用删除线提示而已。
如果想要生成doc帮助文档的话,可以安装Deprecated模块结合使用。
pip install Deprecated
安装之后像下面这样使用即可:
import warnings
from deprecated.sphinx import deprecated
warnings.filterwarnings("always")
@deprecated(version='1.0', reason="This function will be removed soon")
def some_old_function(x, y):
warnings.warn("some_old_function is deprecated", DeprecationWarning)
return x + y
if __name__ == '__main__':
some_old_function(12, 34)
help(some_old_function)
执行之后的结果如下:
@deprecated注解会更改函数的__doc__属性,可以看到帮助文档被打印了出来。如果想要打印出告警信息的话,需要在前面加上warnings.filterwarnings("always")
这样就能看到打印出来的告警信息了。