![](/img/trans.png)
[英]I declare a global variable inside a function, but outside the function it is "undefined", it also says inside the function that it is undefined
[英]declare variable type inside function
我正在定義一個 function 以字節為單位獲取 pdf,所以我寫道:
def documents_extractos(pdf_bytes: bytes):
pass
當我調用 function 時不幸傳遞了一個錯誤的類型,而不是字節,讓我們說一個 int,為什么我沒有收到錯誤? 我已閱讀有關打字的文檔,但我不明白。 為什么告訴 function 變量應該是 bytes 但是當你傳遞和 int 時沒有錯誤? 這可以由isinstance(var, <class_type>)
處理,對嗎? 沒看懂 =(
在頁面頂部,您鏈接的文檔包含一條說明(強調我的):
Python 運行時不強制執行 function 和變量類型注釋。 它們可以被第三方工具使用,例如類型檢查器、IDE、linters 等。
類型提示的目的是用於 static 類型檢查工具(例如mypy
),它使用 static 分析來驗證您的代碼是否遵守書面類型提示。 這些工具必須作為單獨的進程運行。 它們的主要用途是確保大型代碼庫中的新更改不會引入潛在的類型問題(最終可能成為難以解決的潛在錯誤)。
如果您想要顯式運行時類型檢查(例如,如果將錯誤類型的值傳遞給函數,則引發Exception
),請使用isinstance()
。
默認情況下 python 在運行時忽略類型提示,但是 python 在執行代碼時保留類型信息。 感謝這個庫,作者可以實現運行時類型檢查包,例如typeguard 、 pydantic或beartype 。
如果您不想自己使用isinstance
檢查,則可以使用其中一個庫。
類型保護示例:
主要文件:
from typeguard import importhook
importhook.install_import_hook('mypack')
import mypack
mypack.documents_extractos("test")
我的包.py
def documents_extractos(pdf_bytes: bytes):
pass
當您運行python3 main.py
時,您將收到錯誤TypeError: type of argument "pdf_bytes" must be bytes-like; got str instead
TypeError: type of argument "pdf_bytes" must be bytes-like; got str instead
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.