前言
因爲python是動態語言,特別是類似網絡請求返回參數,在還沒收到請求前都不知道參數類型,導致沒法用自動提示,如圖:resp沒法提示.decode()之類的
pycharm幫助文檔有提供類型定義,方便我們自動智能提示
解決方案
1. 指定函數的參數類型:
如果爲以下則指定param爲str類型:
def f(param: str):
如果爲以下則指定param爲str類型,但可以不傳入參數(就是可以爲f()):
def f(param: str = None):
如果爲以下則指定param爲str類型和Bool類型:
def f(param: Union[str, bool]):
如果爲以下則可選param爲str類型:
def f(param: Optional[str] = None):
2. 指定函數的返回參數類型:
但如果如下圖就不行,因爲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以上版本可用的,轉換變量:
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. 運行時(調試)收集對象類型:
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 打開
注意:該選項會把調試運行時間耗時加長!
並且在
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模式運行一遍的情況下,對方法調用(Alt+ Enter),選擇【 Insert documentation string stub】,就能自動對註釋的參數類型進行定義