PYTHONL Telegram 5085
🔥 Подборка небанальных Python-трюков, которые реально упрощают жизнь разработчику

🌀 1. functools.cached_property — ленивое свойство с кэшем
Позволяет вычислить значение один раз и потом возвращать готовый результат.


from functools import cached_property
import time

class DataFetcher:
@cached_property
def heavy_data(self):
print(" Запрос к API...")
time.sleep(2)
return {"status": "ok", "data": [1, 2, 3]}

obj = DataFetcher()
print(obj.heavy_data) # первый вызов → считает
print(obj.heavy_data) # второй вызов → из кэша


🪄 2. contextlib.suppress — игнорируем ошибки красиво

Вместо громоздкого try/except:


import os
from contextlib import suppress

with suppress(FileNotFoundError):
os.remove("tmp.txt")


👉 Идеально для операций, где ошибка — нормальная ситуация (удаление файла, закрытие сокета и т.п.).

🧩 3. Свой контекстный менеджер через enter / exit

Можно сделать объекты, которые сами открываются и закрываются как файлы.


class DemoResource:
def __enter__(self):
print("🔓 Ресурс открыт")
return self

def __exit__(self, exc_type, exc_value, traceback):
print("🔒 Ресурс закрыт")
if exc_type:
print(f"⚠️ Ошибка: {exc_value}")
return True # подавить исключение

with DemoResource() as res:
print(" Работаем...")
raise ValueError("Что-то пошло не так!")


👉 Отлично для работы с ресурсами: подключение к БД, временные настройки, логирование.

@pythonl
10👍9🔥5



tgoop.com/pythonl/5085
Create:
Last Update:

🔥 Подборка небанальных Python-трюков, которые реально упрощают жизнь разработчику

🌀 1. functools.cached_property — ленивое свойство с кэшем
Позволяет вычислить значение один раз и потом возвращать готовый результат.


from functools import cached_property
import time

class DataFetcher:
@cached_property
def heavy_data(self):
print(" Запрос к API...")
time.sleep(2)
return {"status": "ok", "data": [1, 2, 3]}

obj = DataFetcher()
print(obj.heavy_data) # первый вызов → считает
print(obj.heavy_data) # второй вызов → из кэша


🪄 2. contextlib.suppress — игнорируем ошибки красиво

Вместо громоздкого try/except:


import os
from contextlib import suppress

with suppress(FileNotFoundError):
os.remove("tmp.txt")


👉 Идеально для операций, где ошибка — нормальная ситуация (удаление файла, закрытие сокета и т.п.).

🧩 3. Свой контекстный менеджер через enter / exit

Можно сделать объекты, которые сами открываются и закрываются как файлы.


class DemoResource:
def __enter__(self):
print("🔓 Ресурс открыт")
return self

def __exit__(self, exc_type, exc_value, traceback):
print("🔒 Ресурс закрыт")
if exc_type:
print(f"⚠️ Ошибка: {exc_value}")
return True # подавить исключение

with DemoResource() as res:
print(" Работаем...")
raise ValueError("Что-то пошло не так!")


👉 Отлично для работы с ресурсами: подключение к БД, временные настройки, логирование.

@pythonl

BY Python/ django


Share with your friend now:
tgoop.com/pythonl/5085

View MORE
Open in Telegram


Telegram News

Date: |

Hui said the messages, which included urging the disruption of airport operations, were attempts to incite followers to make use of poisonous, corrosive or flammable substances to vandalize police vehicles, and also called on others to make weapons to harm police. How to create a business channel on Telegram? (Tutorial) During a meeting with the president of the Supreme Electoral Court (TSE) on June 6, Telegram's Vice President Ilya Perekopsky announced the initiatives. According to the executive, Brazil is the first country in the world where Telegram is introducing the features, which could be expanded to other countries facing threats to democracy through the dissemination of false content. 6How to manage your Telegram channel? Channel login must contain 5-32 characters
from us


Telegram Python/ django
FROM American