對于PyCharm某些庫沒有自動提示的處理

前言

因為python是動態(tài)語言,特別是類似網(wǎng)絡(luò)請求返回參數(shù),在還沒收到請求前都不知道參數(shù)類型,導致沒法用自動提示,如圖:

resp沒法提示.decode()之類的
pycharm幫助文檔有提供類型定義,方便我們自動智能提示

解決方案

1. 指定函數(shù)的參數(shù)類型:


如果為以下則指定param為str類型:

def f(param: str):

如果為以下則指定param為str類型,但可以不傳入?yún)?shù)(就是可以為f()):

def f(param: str = None):

如果為以下則指定param為str類型和Bool類型:

def f(param: Union[str, bool]):

如果為以下則可選param為str類型:

def f(param: Optional[str] = None):

2. 指定函數(shù)的返回參數(shù)類型:


但如果如下圖就不行,因為Python在定義類之前不允許引用類對象:



所以可以改為:

class ToDo(Base):
    __tablename__ = 'todo'
    id = Column(Integer, primary_key=True)
    title = Column(Text)

    @classmethod
    def list(cls) -> List['ToDo']:
        return session.query(cls).order_by(cls.title)

3. 指定局部變量屬性的類型:

4. 預期類型來進行判斷操作:

5. python3.6以上版本可用的,轉(zhuǎn)換變量:

3.6之前:

from typing import List, Optional
xs = []  # type: List[Optional[str]]

3.6之后

from typing import List, Optional
xs: List[Optional[str]] = []

注意:以上5種方法,如果光標在想注釋的變量上,按快捷鍵??(Alt + Enter),就能用選項選擇來快捷生成

6. 運行時(調(diào)試)收集對象類型:

File | Settings | Build, Execution, Deployment | Python Debuggerfor Windows and Linux
PyCharm | Preferences | Build, Execution, Deployment | Python Debugger for macOS
把Collect run-time types information for code insight 打開
注意:該選項會把調(diào)試運行時間耗時加長!


并且在
File | Settings | Editor | General | Smart Keys for Windows and Linux
PyCharm | Preferences | Editor | General | Smart Keys for macOS
Smart Keys中,把【Insert type placeholders in the documentation comment stub】打開

那么在debug模式運行一遍的情況下,對方法調(diào)用(Alt+ Enter),選擇【 Insert documentation string stub】,就能自動對注釋的參數(shù)類型進行定義

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容