← Назад к вопросам
Что появилось в последних версиях Python?
3.0 Senior🔥 121 комментариев
#DevOps и инфраструктура
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI23 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Новое в последних версиях Python
Обзор версий (Python 3.10 - 3.13)
После выхода Python 3.9 было множество улучшений. Вот самые важные.
Python 3.10 (октябрь 2021)
1. Structural Pattern Matching (match/case)
# ❌ Старый способ (if-elif-else)
def describe_number(n):
if n < 0:
return "negative"
elif n == 0:
return "zero"
elif n > 0:
return "positive"
# ✅ Новый способ (match-case)
def describe_number(n):
match n:
case 0:
return "zero"
case 1 | 2 | 3: # или
return "small positive"
case _ if n < 0:
return "negative"
case _:
return "other"
describe_number(0) # "zero"
describe_number(2) # "small positive"
describe_number(-5) # "negative"
Паттерны по типам:
def handle_response(response):
match response:
case {"status": 200, "data": data}: # Dictionary pattern
return f"Success: {data}"
case {"status": 404}:
return "Not found"
case [first, *rest]: # Sequence pattern
return f"First: {first}, Rest: {rest}"
case Point(x=0, y=0): # Class pattern
return "Origin"
case int() | float(): # Type pattern
return "Number"
case _:
return "Unknown"
2. Union type с |
# ❌ Старый способ
from typing import Union
def process(value: Union[int, str, None]) -> Union[str, int]:
pass
# ✅ Новый способ (Python 3.10+)
def process(value: int | str | None) -> str | int:
pass
list[int] # Также работает для стандартных типов
dict[str, int] # Не нужно List[int], Dict[str, int]
3. Лучшие сообщения об ошибках
# ❌ Python 3.9
# IndentationError: expected an indented block
# (неясно, где проблема)
# ✅ Python 3.10
# IndentationError: expected an indented block (line 5)
# + показывает точное место с ^^
Python 3.11 (октябрь 2022)
1. Faster CPython — производительность + 10-60%
# Просто обновляешься на 3.11 — и код работает быстрее
# Никаких изменений не требуется
# Бенчмарк:
# Python 3.10: 1000 ms
# Python 3.11: 600 ms # На 40% быстрее!
2. Exception Groups и except (правильная обработка multiple errors)*
# ❌ Старый способ — можно ловить только одну ошибку
try:
# Код который может выбросить разные ошибки
except ValueError:
pass
except KeyError:
pass
# ✅ Новый способ — Exception Group
try:
# Код
except* ValueError as ve:
print(f"Value errors: {ve}")
except* KeyError as ke:
print(f"Key errors: {ke}")
# Полезно в asyncio
async def main():
try:
results = await asyncio.gather(
task1(),
task2(),
task3(),
return_exceptions=True
)
except* asyncio.TimeoutError as te:
print(f"Timeout errors: {te}")
3. Task groups в asyncio
# ❌ Python 3.10
async def old_way():
tasks = [
asyncio.create_task(fetch_user(1)),
asyncio.create_task(fetch_user(2)),
asyncio.create_task(fetch_user(3))
]
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, Exception):
print(f"Error: {result}")
else:
print(f"Success: {result}")
# ✅ Python 3.11
async def new_way():
async with asyncio.TaskGroup() as tg:
task1 = tg.create_task(fetch_user(1))
task2 = tg.create_task(fetch_user(2))
task3 = tg.create_task(fetch_user(3))
# Автоматически ждёт, обрабатывает ошибки
4. Self type
from typing import Self
class Builder:
def set_name(self, name: str) -> Self: # Возвращает сам класс
self.name = name
return self
def set_value(self, value: int) -> Self:
self.value = value
return self
# Fluent API
builder = Builder().set_name("test").set_value(42)
# Без Self нужно было писать -> "Builder"
# А с Self автоматически работает с наследованием
class AdvancedBuilder(Builder):
pass
advanced = AdvancedBuilder().set_name("test") # Возвращает AdvancedBuilder
Python 3.12 (октябрь 2023)
1. Per-Interpreter GIL (удаление GIL на один шаг)
# Это шаг к многопоточности без GIL
# Экспериментально, но важно
# Можно запустить Python с --disable-gil
# python --disable-gil script.py
# True многопоточность!
import threading
def worker():
total = 0
for i in range(50_000_000):
total += i
return total
# На 3.12 с --disable-gil это реально параллельно
threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
2. Type parameters (Generic типы проще)
# ❌ Python 3.11
from typing import TypeVar, Generic
T = TypeVar('T')
class Container(Generic[T]):
def __init__(self, item: T):
self.item = item
def get(self) -> T:
return self.item
# ✅ Python 3.12
class Container[T]:
def __init__(self, item: T):
self.item = item
def get(self) -> T:
return self.item
# Намного чище!
c: Container[int] = Container(42)
value: int = c.get()
3. f-string improvements
# ✅ Nested f-strings (теперь работают без экранирования)
values = [1, 2, 3]
result = f"Values: {[f'item-{x}' for x in values]}"
print(result) # "Values: ['item-1', 'item-2', 'item-3']"
# ✅ Реиспользование переменных в f-string
user = {"name": "Alice", "age": 30}
text = f"User: {user['name']}, age {user['age']}"
# ✅ Отладка f-strings
name = "Alice"
age = 30
print(f"{name=}") # name='Alice'
print(f"{age=}") # age=30
Python 3.13 (октябрь 2024)
1. Полное удаление GIL (экспериментально)
# Это НЕ включено по умолчанию
# Но работает в экспериментальной версии
# True параллельная многопоточность!
# Значит: многопоточные приложения станут в 2-4x быстрее
2. Improved error messages
# ❌ Старое сообщение
NameError: name 'user' is not defined
# ✅ Новое сообщение (3.13)
NameError: name 'user' is not defined. Did you mean: 'users'?
# (если есть переменная users в scope)
3. Incremental Garbage Collection
# GC теперь работает постепенно
# Вместо одного большого паузы, много маленьких
# Значит: меньше lag в приложениях
Мой TOP 5 улучшений за последние версии
top_improvements = {
1: "Match/case (структурированная обработка данных)",
2: "Faster CPython (10-60% производительность)",
3: "Union с | (читаемость типов)",
4: "TaskGroup в asyncio (правильная обработка ошибок)",
5: "Removal of GIL (future real multithreading)"
}
Практический пример: миграция кода
# Python 3.10+ — новый код
from typing import Self
import asyncio
class APIClient:
def __init__(self):
self.base_url: str | None = None
self.timeout: int | None = None
def set_base_url(self, url: str) -> Self:
self.base_url = url
return self
def set_timeout(self, timeout: int) -> Self:
self.timeout = timeout
return self
async def fetch(self, endpoint: str) -> dict | list:
async with asyncio.TaskGroup() as tg:
# Параллельные запросы
task1 = tg.create_task(self._get(f"{endpoint}/1"))
task2 = tg.create_task(self._get(f"{endpoint}/2"))
return {"results": [task1.result(), task2.result()]}
async def _get(self, url: str) -> dict:
match url:
case url if url.endswith("/1"):
return {"id": 1, "data": "first"}
case url if url.endswith("/2"):
return {"id": 2, "data": "second"}
case _:
raise ValueError(f"Unknown URL: {url}")
# Использование
client = APIClient().set_base_url("https://api.example.com").set_timeout(30)
result = asyncio.run(client.fetch("/users"))
Какую версию использовать
recommendations = {
"Python 3.13": "Если нужна максимальная производительность",
"Python 3.12": "Production, new projects (хорошо заполированный)",
"Python 3.11": "Production, стабильный и быстрый",
"Python 3.10": "Ещё актуален, но 3.11+ лучше",
"Python < 3.10": "Миграция нужна (выход из поддержки)"
}
Заключение
За последние версии Python получил:
- Лучший синтаксис (match/case, | union, [T])
- Производительность (Faster CPython, улучшенный GC)
- Лучший asyncio (TaskGroup, Exception Group)
- Путь к настоящей многопоточности (GIL removal)
- Лучшие сообщения об ошибках
Если ещё на Python 3.9 — мигрируй на 3.12+. Это стоит того.