Understanding type annotation in Python
Orsan Awawdi
Software Engineer | Extensive experience in automation using Python and Jenkins
Why do we need type hints in Python?
We can annotate (comment) variables and functions with data types. Being a dynamically typed language, the datatype of a variable in Python is determined at runtime. As a python developer, you no longer need to declare the data type of the variable. Being so flexible also introduces some inconveniences, like errors detected at runtime that could have been avoided at the development time.
So why do we need it?
Type hints allow developers to stick to the data type the variable or the function was expecting.?
The Developer can use a linter or a tool (like mypy, pytype) to perform type check, and provide hints or warnings when these types are used incorrectly, and prevent unwanted errors on later stages. Plus, the code will be slowly documented and more readable.?
So how do I add type hints to variables?
variable_name: type = value
This will declare a variable name of a type and assign it to a value. You can do it the right way like:
name: string= "Lisa", but in case you do it the wrong way
name: int = "Lisa"
python interpreter won’t trigger an error, but a type checker like mypy will flag this as an error.
Can I add type hints to functions?
Yes.
def my_function(language: str, version: float) -> str:
领英推荐
The function now has type hint showing that it receives str and float arguments, and returns str.
Can there be more than one type?
Yes.
def view_type(num: str | int) -> None:
We can add union | to show that the parameter num is either str or int.
Can type hints be added to dictionaries?
Yes.
grades: dict[str, int] = { "Homer": 100, "Marge": 90}
And tuples?
Yes.
student: tuple[str, int] = ("Bart", 18)
Type hinting in python can be very useful, it can give developers a way to make their code readable,? self-described, and can reduce heavy headaches when searching for bugs.?