Optional
Giống như Union[X, None]
, dùng cho giá trị có thể bị bỏ qua:
from typing import Optional
def greet(name: Optional[str] = None):
if name:
print(f"Chào bạn, {name}!")
else:
print("Chào bạn, người lạ!")
greet("Nam") # In: Chào bạn, Nam!
greet() # In: Chào bạn, người lạ!
Kết hợp với TypedDict
from typing import TypedDict, Optional
class User(TypedDict):
username: str
email: Optional[str] # Email có thể không tồn tại
def display_email(user: User):
if user["email"]:
print("Email:", user["email"])
else:
print("Không có email.")
Tác giả: Đỗ Ngọc Tú
Công Ty Phần Mềm VHTSoft
Không có bình luận