TGViewer
PyCoders (پایتون) PyCoders (پایتون) @python_rd · 4.11K subscribers
Post #2239 206
🔆 مدیریت تمیز منابع با Context Managerهای سفارشی (contextlib)

🔹 ساخت Context Managerها معمولاً با نوشتن کلاس و متدهای enter و exit انجام می‌شود. اما با دکوراتور contextmanager@ از ماژول contextlib می‌توانید این کار را خیلی سریع‌تر و پایتونیک‌تر انجام دهید.

from contextlib import contextmanager
import time


@contextmanager
def measure_time(task_name: str):
start_time = time.perf_counter()
print(f"--- شروع: {task_name} ---")
try:
yield # کنترل اجرا در این نقطه به بدنه with منتقل می‌شود
finally:
elapsed = time.perf_counter() - start_time
print(f"--- پایان: {task_name} | زمان اجرا: {elapsed:.4f} ثانیه ---\n")


# استفاده کاربردی
with measure_time("پردازش سنگین داده‌ها"):
# شبیه‌سازی یک کار سنگین
total = sum(i**2 for i in range(10_000_000))
print(f"نتیجه محاسبات: {total}")

🐍 @python_rd
More from @python_rd
  1. Oct 13, 2026کوییز پایتون 🔆 خروجی اجرای کد زیر چیست؟ t = (1, 2, [3, 4]) try: t[2] += [5] except TypeEr…
  2. Oct 13, 2026🔆 راز مکانیزم پیاده‌سازی و تغییر جهت NaN در الگوریتم مرتب‌سازی پایتون (Timsort) 🔹 باگ ری…
  3. Oct 13, 2026🔆 حذف تاریخی GIL از پایتون (Free-threaded Python) 🔹 یک رویداد تاریخی: حذف قفل مفسر (GIL)…
  4. Oct 10, 2026🔆 چرا برای داده‌های حجیم نباید از return استفاده کنی؟ 🔹 وقتی یک تابع لیست بزرگی از داده‌…
  5. Oct 10, 2026🔆 خروجی این تکه کد چیه؟ def add_item(item, lst=[]): lst.append(item) return lst print(add…
  6. Oct 10, 2026🔆 مدیریت منابع با contextlib 🔹 از تکرار try...finally برای بستن فایل‌ها و اتصال‌ها خسته…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →