Handling types with Python


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:
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])

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


from typing import Union

def func(arg: Union[int, str]) -> Union[int, str]:
    #         ^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^ 
    #           type of arg         return type

No comments

(optional field, I won't disclose or spam but it's necessary to notify you if I respond to your comment)
All html tags except <b> and <i> will be removed from your comment. You can make links by just typing the url or mail-address.
Anti-spam question: