typing
— 支援類型提示
該模塊為 類型提示
提供運行時支持。最基本的支持包括類型 Any、Union、Callable等等。
有關其完整規範,請參閱 PEP 484。
有關類型提示的簡化介紹,請參閱 PEP 483。
This module provides runtime support for type hints. The most fundamental support consists of the types
typing
— Support for type hintsAny
,Union
,Callable
,TypeVar
, andGeneric
. For a full specification, please see PEP 484. For a simplified introduction to type hints, see PEP 483.
General Type Hints
方法上的類型提示:
Function -> type hints
def funcHints(s: str) -> str:
return "result"
變數上的類型提示:
Variable -> Type hints
Vars: int = 1
字典上的類型提示:
Dict -> Type hints
from typing import TypedDict
class Movie(TypedDict):
name: str
year: int
movie: Movie = {'name': 'Blade Runner', 'year': 1982}
General Variable Type
Type hints -> Any
# import module
from typing import Any
def funcHints(s: str) -> Any:
return "result"
Type hints -> NoReturn
from typing import NoReturn
def stop() -> NoReturn:
raise RuntimeError('no way')
Aliases Type
from typing import Dict, Tuple
ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]
S1: Server = (
( "127.0.0.1", 8080),
{
"allow": "*"
}
)
New Type
from typing import NewType
index: NewType('index', int)
ID: index = 1
Type checker
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
Pylance in VS Code IDE
Pylance是以微軟的靜態類型檢查工具Pyright作為基礎開發,可提供高效能的Python開發體驗,Pylance能提供豐富的類型資訊,強化Python IntelliSense功能,協助開發人員編寫高品質的程式碼,Pylance還附帶了熱門模組的型態存根檔(Type Stub)集合,可以快速且準確地執行自動完成和類型檢查功能。
** Quick Start **
- 安裝
- 設定`Type Checking Mode`
參考文獻:
- https://docs.python.org/3/library/typing.html
- https://stackoverflow.com/questions/45829353/python-type-checking-in-vs-code
- https://peps.python.org/pep-0589/