declare variable type inside function

2.7k Views Asked by At

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 =(

2

There are 2 best solutions below

0
BrokenBenchmark On BEST ANSWER

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 (e.g. 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 (e.g. to raise an Exception if a value of a wrong type is passed into a function), use isinstance().

1
oartart On

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