PYTHONL Telegram 4976
🐍 Продвинутый трюк в Python: свой `with` без классов

Хочешь выполнять код до и после блока with, но не писать громоздкий класс с __enter__ и __exit__? Используй @contextmanager из contextlib:


from contextlib import contextmanager
import time

@contextmanager
def timer(label="Block"):
start = time.time()
print(f"[{label}] Start")
try:
yield
finally:
end = time.time()
print(f"[{label}] End — elapsed: {end - start:.3f}s")

# Пример использования
with timer("Download step"):
time.sleep(1.2)


📌 До yield — код до with
📌 После yield — код после with

🔥 Это мощный способ:

- логировать действия,

- временно менять окружение (stdout, переменные, режимы),

- управлять ресурсами, не создавая классы.

@pythonl
15🔥8👍5



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

🐍 Продвинутый трюк в Python: свой `with` без классов

Хочешь выполнять код до и после блока with, но не писать громоздкий класс с __enter__ и __exit__? Используй @contextmanager из contextlib:


from contextlib import contextmanager
import time

@contextmanager
def timer(label="Block"):
start = time.time()
print(f"[{label}] Start")
try:
yield
finally:
end = time.time()
print(f"[{label}] End — elapsed: {end - start:.3f}s")

# Пример использования
with timer("Download step"):
time.sleep(1.2)


📌 До yield — код до with
📌 После yield — код после with

🔥 Это мощный способ:

- логировать действия,

- временно менять окружение (stdout, переменные, режимы),

- управлять ресурсами, не создавая классы.

@pythonl

BY Python/ django


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

View MORE
Open in Telegram


Telegram News

Date: |

Joined by Telegram's representative in Brazil, Alan Campos, Perekopsky noted the platform was unable to cater to some of the TSE requests due to the company's operational setup. But Perekopsky added that these requests could be studied for future implementation. Members can post their voice notes of themselves screaming. Interestingly, the group doesn’t allow to post anything else which might lead to an instant ban. As of now, there are more than 330 members in the group. Telegram iOS app: In the “Chats” tab, click the new message icon in the right upper corner. Select “New Channel.” Matt Hussey, editorial director of NEAR Protocol (and former editor-in-chief of Decrypt) responded to the news of the Telegram group with “#meIRL.” How to create a business channel on Telegram? (Tutorial)
from us


Telegram Python/ django
FROM American