Skip to content

Type annotations / hints in python 类型注解

A way to explicitly declare the intended data types of variables, function parameters, and return values.

Type hints description

Why we need type hints ?

Type hints on IDEType hitns on usinf Function

Usage

Type hints on variable name

Type hints for variableType hints for variableType hitns for functionType hitns for function

type_hints.py

py
# Type hints for: -

# Variable
var1 : str = "string_value"
var2 : int = 10
var3 : bool = True
var4 : float = 3.142

# Class
class Student:
    pass

std1 : Student = Student()

# Data container

# List [a, b, c]
dc_list : list = ["Apple", "Grape", "Mango"]
dc_list2 : list[int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
dc_list3 : list[str] = ["Apple", "Grape", "Mango"]

# Tuple (a, b, c)
dc_tuple: tuple = (1, 2, 3, 4, 5, "end")
dc_tuple2: tuple[int, int, int, int, int, str] = (1, 2, 3, 4, 5, "end")
dc_tuple3: tuple[int, int, int] = (1, 2, 3)

# Set {A, B, C}
dc_set : set = {1, 2, 3, 4, 5, 6}
dc_set : set[int] = {1, 2, 3, 4, 5, 6}
dc_set : set[str] = {"Apple", "Grape", "Mango"}

# Dictionary {K: V}
dc_dict : dict = {"name": "John"}
dc_dict2 : dict[str, int] = {"age": 14}

# Str as data container
dc_str: str = "Data container string"

# Parameters & return value
def add(x: float, y: float) -> float:
    print(x + y)

Type hints through comment

Comment type hints

type_hints.py

py
# Type hints throught comments

var_1 = ["apple", 1] # type: list[str | int]

Type hints through comment

Union

We using union type when a dictionary (value) type has more than 1 type

Usage

union.py

py
from typing import Union

student_a : dict[str, Union[str, int]] = {
    "name": "John",
    "age": 15,
    "gender": "Male",
    "prefferedNumber": 6
}

# Equivalent to

student_b : dict[str, str | int] = {
    "name": "John",
    "age": 15,
    "gender": "Male",
    "prefferedNumber": 6
}

Conclusion

Conclusion type hintsConclusion for type hints for functionConclusion for union