Asosiy matnga o'tish
ITIT Interview
Python

Dekoratorlar va context manager

Dekorator nima, functools.wraps, argumentli dekoratorlar, klass dekoratorlari, lru_cache, with bloki, __enter__ va __exit__, contextmanager.

O'rganildi: 0 / 5
Progress

Dekorator

Dekorator — funksiyani qabul qilib, uning xatti-harakatini kengaytirgan yangi funksiya qaytaradigan funksiya. Asl kodni o'zgartirmasdan logging, vaqt o'lchash, keshlash, autentifikatsiya qo'shish uchun.

import functools
import time

def timer(func):
    @functools.wraps(func)                 # asl nom va docstring'ni saqlaydi
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__}: {time.perf_counter() - start:.3f}s")
        return result
    return wrapper

@timer
def load_data():
    time.sleep(1)

load_data()   # load_data: 1.001s

@timer yozuvi shunchaki load_data = timer(load_data) ning qisqartmasi.

functools.wraps siz load_data.__name__ "wrapper" bo'lib qoladi va debug, logging va hujjatlar buziladi.

Argumentli dekorator

Bir daraja ko'proq ichma-ichlik kerak: avval argumentlarni qabul qiladigan funksiya, u dekoratorni qaytaradi:

def retry(times=3, exceptions=(Exception,)):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except exceptions:
                    if attempt == times:
                        raise
                    time.sleep(2 ** attempt)
        return wrapper
    return decorator

@retry(times=5, exceptions=(ConnectionError,))
def fetch_rates():
    ...

Bir nechta dekorator

@login_required     # 2. tashqi
@cache_result       # 1. ichki — avval qo'llanadi
def dashboard(): ...
# dashboard = login_required(cache_result(dashboard))

O'rnatilgan foydali dekoratorlar

from functools import lru_cache, cache

@lru_cache(maxsize=128)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

fib(100)   # darhol — natijalar keshlangan

Boshqalari: @property, @staticmethod, @classmethod, @dataclass, @functools.singledispatch.

Context manager

Context manager resursni olish va bo'shatishni kafolatlaydi: with bloki qanday tugashidan qat'i nazar (xato bilan ham), tozalash kodi bajariladi.

with open("data.txt", encoding="utf-8") as f:
    data = f.read()
# fayl bu yerda albatta yopilgan, hatto xato bo'lsa ham

Ishlatilishi: fayllar, DB ulanishlari va tranzaksiyalar, qulflar (with lock:), vaqtinchalik sozlamalar.

Klass bilan

class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self                        # `as` ga beriladigan qiymat

    def __exit__(self, exc_type, exc, tb):
        self.elapsed = time.perf_counter() - self.start
        return False                       # True qaytarsa — xato yutib yuboriladi

with Timer() as t:
    heavy_work()
print(t.elapsed)

contextmanager bilan

from contextlib import contextmanager

@contextmanager
def transaction(conn):
    cur = conn.cursor()
    try:
        yield cur                # with bloki shu yerda bajariladi
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        cur.close()

with transaction(conn) as cur:
    cur.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")

Intervyu savollari

Ushbu sahifada