简体   繁体   中英

declare variable type inside function

I am defining a function that gets pdf in bytes, so I wrote:

def documents_extractos(pdf_bytes: bytes):
    pass

When I call the function and unfortunately pass a wrong type, instead of bytes let's say an int, why I don't get an error? I have read the documentation regarding typing but I don't get it. Why is the purpose of telling the function that the variable shoudl be bytes but when you pass and int there is no error? This could be handle by a isinstance(var, <class_type>) right? I don't understand it =(

Type hints are ignored at runtime.

At the top of the page, the documentation that you've linked contains a note that states (emphasis mine):

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.

The purpose of type hints is for static typechecking tools (eg mypy ), which use static analysis to verify that your code respects the written type hints. These tools must be run as a separate process. Their primary use is to ensure that new changes in large codebases do not introduce potential typing issues (which can eventually become latent bugs that are difficult to resolve).

If you want explicit runtime type checks (eg to raise an Exception if a value of a wrong type is passed into a function), use isinstance() .

By default python ignores type hints at runtime, however python preserves the type information when the code is executed. Thanks to this library authors can implement runtime type checking packages such as typeguard , pydantic or beartype .

If you don't want to use isinstance checks yourself, you can use one of those libraries.

Typeguard example:

main.py:

from typeguard import importhook
importhook.install_import_hook('mypack')

import mypack


mypack.documents_extractos("test")

mypack.py

def documents_extractos(pdf_bytes: bytes):
    pass

When you run python3 main.py you will get error 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM