Skip to content

Latest commit

 

History

History
27 lines (23 loc) · 467 Bytes

File metadata and controls

27 lines (23 loc) · 467 Bytes

Custom Context Managers & contextlib

Custom Context Manager

class MyCtx:
    def __enter__(self):
        print('Enter')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Exit')

with MyCtx():
    print('Inside')

contextlib.contextmanager

from contextlib import contextmanager
@contextmanager
def simple():
    print('Start')
    yield
    print('End')

with simple():
    print('Doing work')