Handling types with Python
Some notes and pointers on using types with Python - 04/2023 - #Jumble
https://realpython.com/python-type-checking/
Summary:
In Python you can define type hints:
def headline(text: str, align: bool = True) -> str:They won't trigger any errors at runtime, but you can run static type checkers to verify your code before you execute it. PyCharm/Rider will check the type hints for you on the go as well. On big projects this may be beneficial to make it a rule to use as much type hints as possible? Only from Python 3.5 though, and for complex types such as list of strings you need extra packages:
from typing import List aVariable : List[str] = ["1", "2"]
Dynamic type checking:
https://stackoverflow.com/a/57813576/2273600
The library typeguard
can automatically do runtime type checks wherever you want.
Checking types directly is also supported.
from typeguard import check_type # Raises TypeError if there's a problem check_type('variablename', [1234], List[int])
Comment:
Better yet, typeguard's @typechecked decorator lets you automatically do typehint validation on all inputs and outputs to a function. Or, if you slap it on a class definition, it'll do runtime validation on all of its methods
Handling multiple input and output types:
https://stackoverflow.com/a/64828452/2273600
You can use
def func(arg: int | str) -> int | str: # ^^^^^^^^^ ^^^^^^^^^ # type of arg return type
Or
from typing import Union def func(arg: Union[int, str]) -> Union[int, str]: # ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ # type of arg return type
No comments