前言
因?yàn)閜ython是動(dòng)態(tài)語(yǔ)言奏窑,特別是類(lèi)似網(wǎng)絡(luò)請(qǐng)求返回參數(shù)依鸥,在還沒(méi)收到請(qǐng)求前都不知道參數(shù)類(lèi)型,導(dǎo)致沒(méi)法用自動(dòng)提示舟陆,如圖:resp沒(méi)法提示.decode()之類(lèi)的
pycharm幫助文檔有提供類(lèi)型定義,方便我們自動(dòng)智能提示
解決方案
1. 指定函數(shù)的參數(shù)類(lèi)型:
如果為以下則指定param為str類(lèi)型:
def f(param: str):
如果為以下則指定param為str類(lèi)型,但可以不傳入?yún)?shù)(就是可以為f()):
def f(param: str = None):
如果為以下則指定param為str類(lèi)型和Bool類(lèi)型:
def f(param: Union[str, bool]):
如果為以下則可選param為str類(lèi)型:
def f(param: Optional[str] = None):
2. 指定函數(shù)的返回參數(shù)類(lèi)型:
但如果如下圖就不行腐芍,因?yàn)镻ython在定義類(lèi)之前不允許引用類(lèi)對(duì)象:
所以可以改為:
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. 指定局部變量屬性的類(lèi)型:
4. 預(yù)期類(lèi)型來(lái)進(jìn)行判斷操作:
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種方法试躏,如果光標(biāo)在想注釋的變量上猪勇,按快捷鍵??(Alt + Enter),就能用選項(xiàng)選擇來(lái)快捷生成
6. 運(yùn)行時(shí)(調(diào)試)收集對(duì)象類(lèi)型:
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 打開(kāi)
注意:該選項(xiàng)會(huì)把調(diào)試運(yùn)行時(shí)間耗時(shí)加長(zhǎng)颠蕴!
并且在
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】打開(kāi)
那么在debug模式運(yùn)行一遍的情況下助析,對(duì)方法調(diào)用(Alt+ Enter),選擇【 Insert documentation string stub】椅您,就能自動(dòng)對(duì)注釋的參數(shù)類(lèi)型進(jìn)行定義