Python

Custom context managers (contextlib)

Në shqip: Context manager-at e tu

ShpjegimiSQ

Mund ta bësh objektin tënd të punojë me with duke shkruar __enter__ dhe __exit__, ose më lehtë me @contextmanager dhe yield. Kodi pas yield ekzekutohet gjithmonë në fund, edhe me gabim.

EnglishEN

You can make your own object work with with by writing __enter__ and __exit__, or more simply with @contextmanager and yield. The code after yield always runs at the end, even on error.

Si ta mendosh

Si drita automatike: ndizet kur hyn, fiket kur del — gjithmonë.

Lexoje në anglisht

Like an automatic light: on when you enter, off when you leave — always.

Shembull kodipython

from contextlib import contextmanager
@contextmanager
def kohematës():
    import time; t = time.perf_counter(); yield
    print(f"{time.perf_counter() - t:.2f}s")

Terma të lidhur