Python标记函数或类为废弃(deprecated)并在Pychram或Idea中检测提⽰删
除线
⽂章⽬录
前⾔
在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")
python转java代码
@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")
这样就能看到打印出来的告警信息了。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。