All categories
    PythonAdvanced

    Context Managers

    Python context managers and the with statement: manage resources safely, build custom managers, and use contextlib decorators.

    01With statement for files

    main.py
    with open("data.txt", "w") as f:
        f.write("Python")
    
    with open("data.txt") as f:
        print(f.read())
    Output
    Python

    02Custom context manager

    main.py
    class Timer:
        def __enter__(self):
            print("Start")
            return self
        def __exit__(self, *args):
            print("End")
    
    with Timer():
        print("Working")
    Output
    Start
    Working
    End

    03contextlib decorator

    main.py
    from contextlib import contextmanager
    
    @contextmanager
    def tag(name):
        print("<" + name + ">")
        yield
        print("</" + name + ">")
    
    with tag("div"):
        print("content")
    Output
    <div>
    content
    </div>