解決Pytorch在IDE中無法自動補全的問題
在使用IDE來寫關於 pytorch
的程式碼時,我們會發現IDE中的自動補全功能無法使用,甚至會給出各種Warning。這是由於 pytorch
絕大部分程式碼由C++實現,由於不是原生的Python程式碼,所以引發了上述問題。那麼,我們如何解決呢?
先google一下,找到pytorch中這個 ofollow,noindex">issue 下的討論。
其中,一個解決方案如下圖所示:

how_to_fix.png
解決方案的關鍵詞為 .pyi
,那麼什麼是 .pyi
檔案呢?我們可以從 PEP484 中獲得瞭解。
Stub files are files containing type hints that are only for use by the type checker, not at runtime. There are several use cases for stub files:
- Extension modules
- Third-party modules whose authors have not yet added type hints
- Standard library modules for which type hints have not yet been written
- Modules that must be compatible with Python 2 and 3
- Modules that use annotations for other purposes
這裡的 Stub files
就包括我們的 .pyi
檔案,這個檔案可以幫助我們新增 type hints
,我們的IDE就是通過這種 type hints 來實現自動補全的。所以,即使pytorch的庫作者團隊沒有給pytorch新增 .pyi
來提供type hints,我們依然可以自己新增這樣的檔案,來幫助IDE實現自動補全的功能。
另外,值得注意的是這樣的檔案只為 type checker使用,在檔案執行時不會產生任何影響。所以,可以大膽使用。
那麼,有沒有已經寫好的 .pyi
檔案呢?Gist中就有這樣的檔案嗎,同時也是上圖中的大神幫忙補全的。 gist地址
我們只要將這個檔案貼上到 pytorch包中即可,命名為 __init__.py 。最終效果如下圖所示,圖中的目錄為torch的目錄。

pyi.png
# 通過下方程式碼定位自己安裝包目錄 import site site.getsitepackages()
最後,我們成功解決了這個問題。

final_result.png