Khi cần kiểm tra xem các phần tử trong tuple có đúng thứ tự kiểu dữ liệu mong đợi hay không, có thể sử dụng hàm isinstance() kết hợp với các điều kiện and (chuỗi điều kiện).
Hàm isinstance(obj, type) kiểm tra xem đối tượng obj có thuộc kiểu type hay không (kế thừa class cũng trả về True).
Chuỗi điều kiện and (chained if) kết hợp nhiều kiểm tra isinstance - tất cả phải True thì kết quả mới là True.
Ví dụ
# Tuple cần kiểm tra: (str, list, int)
my_tuple = ('Hi', ['there', 'Will'], 67)
print(f"Tuple: {my_tuple}")
# Kiểm tra từng vị trí có đúng kiểu mong đợi
# isinstance(my_tuple, tuple) kiểm tra đối tượng gốc là tuple
check_result = (isinstance(my_tuple, tuple) and
isinstance(my_tuple[0], str) and
isinstance(my_tuple[1], list) and
isinstance(my_tuple[2], int))
print(f"\nCó khớp thứ tự kiểu (str, list, int)? {check_result}")
# Ví dụ thất bại
wrong_tuple = ('Hi', 67, ['there', 'Will'])
check_wrong = (isinstance(wrong_tuple, tuple) and
isinstance(wrong_tuple[0], str) and
isinstance(wrong_tuple[1], list) and
isinstance(wrong_tuple[2], int))
print(f"Tuple sai thứ tự {wrong_tuple} -> {check_wrong}")
Kết quả
Tuple: ('Hi', ['there', 'Will'], 67)
Có khớp thứ tự kiểu (str, list, int)? True
Tuple sai thứ tự ('Hi', 67, ['there', 'Will']) -> False
Giải thích
- Tuple
('Hi', ['there', 'Will'], 67)có cấu trúc: string, list, integer. - Mỗi
isinstance()kiểm tra một vị trí cụ thể. - Toán tử
andđảm bảo tất cả điều kiện phải thỏa mãn. - Nếu tuple ngắn hơn hoặc dài hơn, truy cập index sẽ gây
IndexError.
Cách tổng quát hơn: Hàm kiểm tra schema
def check_tuple_schema(tuple_data, expected_types):
"""
Kiểm tra tuple có khớp schema kiểu dữ liệu không.
Args:
tuple_data: tuple cần kiểm tra
expected_types: list/tuple các kiểu mong đợi (vd: [str, int, list])
Returns:
bool: True nếu khớp hoàn toàn
"""
if not isinstance(tuple_data, tuple):
return False
if len(tuple_data) != len(expected_types):
return False
return all(isinstance(val, typ) for val, typ in zip(tuple_data, expected_types))
# Sử dụng
schema = (str, list, int)
print(check_tuple_schema(('Hi', ['a', 'b'], 42), schema)) # True
print(check_tuple_schema(('Hi', 42, ['a', 'b']), schema)) # False
print(check_tuple_schema(('Hi', ['a']), schema)) # False (thiếu phần tử)
Sử dụng typing.Tuple (Python 3.9+) cho type hint
from typing import Tuple
# Type hint cho tuple (str, list, int)
def process_data(data: Tuple[str, list, int]) -> None:
# Static type checker (mypy) sẽ cảnh báo nếu sai kiểu
pass