
Python 3.12: Tính năng mới và hiệu suất cải thiện
Python 3.12 được phát hành vào tháng 10/2023, đánh dấu một bước tiến quan trọng về hiệu suất và developer experience. Với những cải tiến đáng kể từ PEP 684 đến PEP 701, Python 3.12 là phiên bản đáng để nâng cấp.
Nội dung chính
Hiệu suất cải thiện đáng kể
Python 3.12 nhanh hơn 3.11 khoảng 5-10% trong hầu hết các workloads:
- Comprehensions nhanh hơn tới 2x
- Async generators cải thiện 10-15%
- Method calls nhanh hơn 10%
F-string Improvements (PEP 701)
F-strings giờ linh hoạt hơn nhiều:
# Nested f-strings (trước 3.12 không được)
name = "Alice"
greeting = f"Hello, {f'{name.upper()}'}" # Hello, ALICE
# Multi-line expressions
result = f"""
The answer is: {
complex_calculation(
param1=value1,
param2=value2
)
}
"""
# Backslash trong f-string (mới!)
path = f"C:\\Users\\{username}\\Documents"
# Comments trong f-string expression
value = f"{
x # this is x
+ y # plus y
}"Per-Interpreter GIL (PEP 684)
Đây là bước đầu tiên để loại bỏ GIL trong Python. Mỗi sub-interpreter có thể có GIL riêng:
# Concept - API đang phát triển
import interpreters
interp = interpreters.create()
# Mỗi interpreter có GIL riêng
# Cho phép true parallelism trong một processTính năng này vẫn experimental nhưng mở ra tương lai multi-threading thực sự cho Python.
Type Parameter Syntax (PEP 695)
Cú pháp mới cho generic types, đơn giản và trực quan hơn:
# Python 3.11
from typing import TypeVar, Generic
T = TypeVar('T')
class Container(Generic[T]):
def __init__(self, item: T) -> None:
self.item = item
# Python 3.12 - Cú pháp mới!
class Container[T]:
def __init__(self, item: T) -> None:
self.item = item
# Type alias mới
type Point = tuple[float, float]
type Vector[T] = list[T]
# Generic functions
def first[T](items: list[T]) -> T:
return items[0]Better Error Messages
Python 3.12 tiếp tục cải thiện error messages:
# Import errors rõ ràng hơn
>>> from datetime import datatime
NameError: cannot import name 'datatime' from 'datetime'.
Did you mean: 'datetime'?
# Syntax errors chi tiết hơn
>>> match value
File "", line 1
match value
^
SyntaxError: expected ':' Deprecated: distutils
distutils chính thức bị remove. Sử dụng setuptools hoặc packaging thay thế:
# Thay thế distutils.version
from packaging.version import Version
v = Version("1.2.3")
print(v.major) # 1Các thay đổi khác
pathlib.Path.walk()– Tương tự os.walk() nhưng cho Pathitertools.batched()– Chia iterable thành batches- SQLite 3.37 support
- Improved asyncio performance
Cách nâng cấp
# Ubuntu/Debian
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.12
# macOS với Homebrew
brew install python@3.12
# pyenv
pyenv install 3.12.0
pyenv global 3.12.0Fullstack Station Tips
Python 3.12 là bản nâng cấp tuyệt vời. Những điểm mình thích nhất:
- Type parameter syntax – Viết generic code đẹp hơn nhiều
- F-string improvements – Không còn những workarounds kỳ lạ
- Performance – 5-10% nhanh hơn là đáng kể cho production
Nếu bạn đang dùng Python 3.10 hoặc 3.11, mình khuyên nâng cấp. Hầu hết libraries phổ biến đã hỗ trợ 3.12. Chạy test suite kỹ vì một số deprecated APIs đã bị remove.
