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: |

As five out of seven counts were serious, Hui sentenced Ng to six years and six months in jail. ZDNET RECOMMENDS How to create a business channel on Telegram? (Tutorial) A few years ago, you had to use a special bot to run a poll on Telegram. Now you can easily do that yourself in two clicks. Hit the Menu icon and select “Create Poll.” Write your question and add up to 10 options. Running polls is a powerful strategy for getting feedback from your audience. If you’re considering the possibility of modifying your channel in any way, be sure to ask your subscribers’ opinions first. In handing down the sentence yesterday, deputy judge Peter Hui Shiu-keung of the district court said that even if Ng did not post the messages, he cannot shirk responsibility as the owner and administrator of such a big group for allowing these messages that incite illegal behaviors to exist.
from us


Telegram Python/ django
FROM American