MyPy1 是 Python 的靜態型別檢查器。與 C 或 Java 等靜態類型語言不同,Python 是動態類型的。這意味著在 Python 中,您不必明確聲明變數的類型;它是在運行時推斷的。例如:
num = 4 # `num` is inferred as an integer newString = "new string" # `newString` is inferred as a string
相反,靜態類型語言要求您在編譯時指定每個變數的類型。這有助於在開發期間而不是在運行時捕獲與類型相關的錯誤。
int num = 4; // `num` is declared as an integer std::string newString = "new string"; // `newString` is declared as a string
在Python等動態類型語言中,運行時可能會發生類型錯誤,這可能會導致更難以追蹤的錯誤。 MyPy 透過允許您在 Python 程式碼中新增類型提示來解決這個問題,這些提示可以在執行前進行靜態檢查。這提供了幾個優點:
這是一個簡單的範例,示範了 MyPy 中類型提示的使用:
def add(a, b): return a b print(add(5, 3)) # Output: 8 print(add("hello", "world")) # Output: helloworld
在上面的程式碼中,add 函數可以接受整數和字串,這可能不是預期的行為。
def add(a: int, b: int) -> int: return a b print(add(5, 3)) # Output: 8 # mypy will report an error for the following line: # print(add("hello", "world")) # TypeError: Expected int, got str
透過包含類型提示(a: int、b: int),您可以指定 add 只適用於整數。 MyPy 根據這些類型提示檢查程式碼,儘早發現潛在的類型相關問題。
開始使用 MyPy:
python3 -m pip install mypy
mypy program.py
此命令將靜態檢查您的程式碼,類似於編譯器檢查 C 中的語法的方式。它將報告它發現的任何類型錯誤,而無需實際運行程式碼。
有效地使用 MyPy 可讓您將靜態類型的優點整合到 Python 中,同時仍可享受其動態特性的靈活性。
def greeting(name): return 'Hello ' name # These calls will fail when the program runs, but MyPy will not report an error greeting(123) greeting(b"Aniket")
透過新增類型註釋(也稱為類型提示),MyPy 可以檢測潛在問題:
def greeting(name: str) -> str: return 'Hello ' name greeting(3) # mypy will report: Argument 1 to "greeting" has incompatible type "int"; expected "str" greeting(b'Alice') # mypy will report: Argument 1 to "greeting" has incompatible type "bytes"; expected "str" greeting("World!") # No error
這裡:
MyPy 在多種情況下很有用:
儘早捕獲錯誤:在運行程式碼之前使用 MyPy 尋找與類型相關的錯誤。這有助於及早發現錯誤並提高程式碼可靠性。
使程式碼更清晰:添加類型提示使您的程式碼更易於理解。它顯示了期望的值類型,這有助於其他人(以及未來的你)更好地理解你的程式碼。
升級舊程式碼:更新舊程式碼時,MyPy 在新增類型提示時協助尋找型別問題,讓過渡更加平滑。
改進原型:建立新功能或原型時,MyPy 透過強制執行類型規則來幫助確保新程式碼與現有程式碼正確配合。
維護大型專案:在有許多貢獻者的大型專案中,MyPy 有助於保持程式碼一致性並防止與類型相關的錯誤。
Boost IDE 功能:如果您使用 IDE,MyPy 改進了程式碼完成和導航等功能,讓開發更容易。
使用 MyPy 可以幫助您編寫更好、更可靠的 Python 程式碼,同時仍然享受 Python 的靈活性。
mypy 的官方快速備忘單
官方文件↩
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3