[英]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.