Zen of Python
Полный Дзен Пайтона в одном канале Разместить рекламу: @tproger_sales_bot Правила общения: https://tprg.ru/rules Другие каналы: @tproger_channels Сайт: https://tprg.ru/site Регистрация в перечне РКН: https://tprg.ru/xZOL
Show more📈 Analytical overview of Telegram channel Zen of Python
Channel Zen of Python (@zen_of_python) in the Russian language segment is an active participant. Currently, the community unites 18 714 subscribers, ranking 7 010 in the Technologies & Applications category and 35 227 in the Russia region.
📊 Audience metrics and dynamics
Since its creation on невідомо, the project has demonstrated rapid growth, gathering an audience of 18 714 subscribers.
According to the latest data from 28 October, 2026, the channel demonstrates stable activity. Although there has been a change in the number of participants by -100 over the last 30 days and by -10 over the last 24 hours, overall reach remains high.
- Verification status: Not verified
- Engagement rate (ER): The average audience engagement rate is 6.22%. Within the first 24 hours after publication, content typically collects 4.24% reactions from the total number of subscribers.
- Post reach: On average, each post receives 1 165 views. Within the first day, a publication typically gains 793 views.
- Reactions and interaction: The audience actively supports content: the average number of reactions per post is 1.
- Thematic interests: Content is focused on key topics such as github, rust, pip, api, install.
📝 Description and content policy
The author describes the resource as a platform for expressing subjective opinions:
“Полный Дзен Пайтона в одном канале
Разместить рекламу: @tproger_sales_bot
Правила общения: https://tprg.ru/rules
Другие каналы: @tproger_channels
Сайт: https://tprg.ru/site
Регистрация в перечне РКН: https://tprg.ru/xZOL”
Thanks to the high frequency of updates (latest data received on 29 October, 2026), the channel maintains relevance and a high level of publication reach. Analytics show that the audience actively interacts with content, making it an important point of influence in the Technologies & Applications category.
# После добавления нового кода
def new_feature():
unused_var = "not used" # Линтер найдет неиспользуемую переменную
return "feature"
⚡️ Проверка совместимости
# После изменения импортов
from new_module import new_function
# Линтер проверит, существует ли new_function
⚡️ Соблюдение стандартов
# После рефакторинга
class MyClass:
def __init__(self):
self.very_long_attribute_name_that_should_be_shorter = None
# Линтер предложит сократить имя
⚡️ Проблемы безопасности
import subprocess
user_input = input("Enter command: ")
subprocess.run(user_input, shell=True) # Линтер предупредит о SQL injection
⚡️ Неэффективный код
# Неэффективно
my_list = []
for i in range(1000):
my_list.append(i)
# Линтер может предложить list comprehension
my_list = [i for i in range(1000)]
Настройка линтера
Обычно линтер настраивается через файлы конфигурации:
# pyproject.toml
[tool.ruff]
line-length = 88 # Максимальная длина строки
target-version = "py38" # Версия Python
Мы можем тонко настраивать, каким именно правилам следовать:
[tool.ruff.lint]
select = ["E", "F", "W", "C90", "I", "N", "UP", "YTT", "S", "BLE", "FBT", "B", "A", "COM", "C4", "DTZ", "T10", "EM", "EXE", "FA", "ISC", "ICN", "G", "INP", "PIE", "T20", "PYI", "PT", "Q", "RSE", "RET", "SLF", "SLOT", "SIM", "TID", "TCH", "INT", "ARG", "PTH", "TD", "FIX", "ERA", "PD", "PGH", "PL", "TRY", "FLY", "NPY", "AIR", "PERF", "FURB", "LOG", "RUF"]
ignore = ["E501", "S101", "PLR0913", "PLR0912", "PLR0915"]
Классические линтеры
🔘Pylint
🔘ruff
🔘Flake8
🔘mypy
🔘black
Пользователи Cursor, возможно, обратили внимание на завтозапуск линтера после практически каждого внесенного изменения. Эта IDE не отдает предпочтения какому-то конкретному инструменту, но запускает несколько из них.
Список правил ruff с детализацией в доках
#основы
@zen_of_pythonhandle(request) и хранит ссылку на «следующего»;
🔘 ConcreteHandler: решает, обрабатывать ли запрос, либо передаёт дальше;
🔘 Client: строит цепочку и отправляет запрос первому звену.
Пример
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Optional, Any, Callable
class Handler(ABC):
def __init__(self, nxt: Optional["Handler"] = None):
self._next = nxt
def set_next(self, nxt: "Handler") -> "Handler":
self._next = nxt
return nxt # позволяет строить цепочку «в линию»
def handle(self, request: Any) -> Any:
# Базовая реализация: попытаться обработать здесь,
# иначе передать дальше.
result = self._handle_here(request)
if result is not None:
return result
if self._next:
return self._next.handle(request)
return None # никто не справился
@abstractmethod
def _handle_here(self, request: Any) -> Optional[Any]:
...
@dataclass
class HttpRequest:
path: str
headers: dict
user_id: Optional[int] = None
payload: Optional[dict] = None
class AuthHandler(Handler):
def _handle_here(self, req: HttpRequest) -> Optional[Any]:
token = req.headers.get("Authorization")
if not token:
# Нет токена — «решение на месте»: отклоняем и НЕ передаём дальше
return {"status": 401, "message": "Unauthorized"}
# валидируем (упростим) и ставим идентификатор
req.user_id = 42
return None # пропускаем дальше
class RateLimitHandler(Handler):
def __init__(self, check: Callable[[HttpRequest], bool], nxt: Optional[Handler] = None):
super().__init__(nxt)
self.check = check
def _handle_here(self, req: HttpRequest) -> Optional[Any]:
if not self.check(req):
return {"status": 429, "message": "Too Many Requests"}
return None
class RouterHandler(Handler):
def _handle_here(self, req: HttpRequest) -> Optional[Any]:
if req.path == "/me" and req.user_id:
return {"status": 200, "data": {"id": req.user_id}}
if req.path == "/ping":
return {"status": 200, "data": "pong"}
# Не мой маршрут — пропускаю дальше (если есть)
return None
class NotFoundHandler(Handler):
def _handle_here(self, req: HttpRequest) -> Optional[Any]:
# Терминальный обработчик: если дошли сюда — 404
return {"status": 404, "message": f"Route {req.path} not found"}
# Сборка цепочки
def build_pipeline() -> Handler:
auth = AuthHandler()
rate = RateLimitHandler(check=lambda r: True)
router = RouterHandler()
notfound = NotFoundHandler()
auth.set_next(rate).set_next(router).set_next(notfound)
return auth
if __name__ == "__main__":
pipeline = build_pipeline()
print(pipeline.handle(HttpRequest(path="/ping", headers={"Authorization": "Bearer x"})))
print(pipeline.handle(HttpRequest(path="/me", headers={"Authorization": "ok"})))
print(pipeline.handle(HttpRequest(path="/unknown", headers={"Authorization": "ok"})))
print(pipeline.handle(HttpRequest(path="/ping", headers={})))
def find_closest_even_divisor(n: int, max_n: int) -> int:
"""
For given n ∈ ℕ and an even N ≥ n, N ∈ ℕ,
find an even ñ closest to n so that ñ is a divisor of N.
If there are several such numbers, pick the largest one.
"""
if max_n <= 0:
raise ValueError(f"There are no positive divisors for {max_n}")
if max_n & 1:
raise ValueError(f"There are no even divisors for {max_n}, which is odd")
if n > 0.75 * max_n:
return max_n
if max_n % n == 0 and n & 1 == 0:
return n
divisors: list[int] = []
dd: int = 1
while max_n > 1 and max_n & 1 == 0:
max_n >>= 1
dd <<= 1
divisors.append(dd)
d: int = 3
dc: list[int]
while max_n > 1:
dc = []
dd = 1
while max_n % d == 0:
max_n //= d
dd *= d
dc.append(dd)
else:
if dc:
divisors += [divisor * dd for divisor in divisors for dd in dc]
if d < isqrt(max_n) and d < 2 * n:
d += 2
else:
break
return min(divisors, key=lambda _d: (abs(n - _d), -_d))
Что ещё можно ускорить?»
NB! Пожалуйста, будьте взаимовежливы. Однажды и вам помогут в этой рубрике.
#обсуждение
@zen_of_python