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")


@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")
這樣就能看到打印出來的告警信息了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章