Python Type Hint
· 約2分
Since Python 3.5, Python introduced Type hint. And it become more and more powerful.
With it You can set the type for your variable for readibility.
Type hints are hints, not enforcements. Python still runs the code even if types don't match.
Usage
# Primitives
name: str = "Tom"
age: int = 30
salary: float = 500.5
is_active: bool = True
# Collections
numbers: list = [1,2,3]
scores: tuple = (90, 85, 88)
unique: set = {1, 2, 3}
data: dict = {"key": "value"}
# Specific Collection Types
from typing import List, Dict, Tuple, Set
names: List[str] = ["Alice", "Bob", "Charlie"]
user: Dict[str, str] = {
"name": "John",
"email": "[email protected]"
}
person: Tuple[str, int, bool] = ("Alice", 30, True)
unique_ids: Set[int] = {1, 2, 3, 4, 5}
# after python 3.9 the following are also work
names: list[str] = ["Alice", "Bob", "Charlie"]
user: dict[str, str] = {
"name": "John",
"email": "[email protected]"
}person: tuple[str, int, bool] = ("Alice", 30, True)
unique_ids: set[int] = {1, 2, 3, 4, 5}
# Optional
from typing import Optional
# can be string or None
middle_name: Optional[str] = None
# Union
from typing import Union
number: Union[int, float] = 10
number = 10.5
# Literal for exact values
from typing import Literal
Status = Literal["pending", "approved", "rejected"]
def process_order(status: Status) -> None:
pass
# TypedDict
from typing import TypedDict
# TypedDict for dictionary structures
class UserDict(TypedDict):
name: str
age: int
email: str
# Class
user: User = get_user(123)
# method
def calculate_bmi(weight: float, height: float) -> float:
return weight / (height ** 2)
# Self
from typing import Self
class User:
def copy(self) -> Self: # Returns same class type
return User()