[{"data":1,"prerenderedAt":66},["ShallowReactive",2],{"qa-\u002Fpython\u002Fexceptions\u002Fcontext-managers":3},{"page":4,"siblings":54,"blog":63},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":45,"seo":46,"seoDescription":47,"stem":48,"subtopic":49,"topic":50,"topicSlug":51,"updated":52,"__hash__":53},"qa\u002Fpython\u002Fexceptions\u002Fcontext-managers.md","Context Managers",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,1,"\u002Fpython\u002Fexceptions\u002Fcontext-managers",[23,28,32,36,41],{"id":24,"difficulty":25,"q":26,"a":27},"what-is-context-manager","easy","What is a context manager and what does the with statement do?","A **context manager** is an object that defines **setup and teardown** logic to run\naround a block of code. The **`with` statement** uses it to guarantee that the\nteardown happens — even if the block raises an exception or returns early — so you\ndon't have to write manual `try\u002Ffinally`.\n\n```python\nwith open(\"data.txt\") as f:   # __enter__ runs, returns the file\n    data = f.read()\n# __exit__ runs here automatically — the file is closed\n```\n\nThe classic use is resource management: files, network sockets, database\nconnections, and locks. Rule of thumb: any \"acquire then must-release\" pattern is\na candidate for a `with` block.\n",{"id":29,"difficulty":14,"q":30,"a":31},"enter-exit","How do __enter__ and __exit__ work?","To make a class a context manager you implement two dunder methods. **`__enter__`**\nruns at the start of the `with` block and its return value is bound to the `as`\nvariable. **`__exit__`** runs when the block ends — always — receiving the\nexception type, value, and traceback (all `None` if the block succeeded).\n\n```python\nclass Timer:\n    def __enter__(self):\n        import time; self.start = time.time()\n        return self                      # bound to 'as t'\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        import time; print(time.time() - self.start)\n        return False                     # don't suppress exceptions\n\nwith Timer() as t:\n    do_work()\n```\n\n`__exit__` always runs, which is what makes cleanup reliable. Rule of thumb:\nacquire the resource in `__enter__`, release it in `__exit__`, and `return self`\nif callers need the object.\n",{"id":33,"difficulty":14,"q":34,"a":35},"contextlib-decorator","How does contextlib.contextmanager simplify writing one?","The **`@contextlib.contextmanager`** decorator lets you write a context manager as a\n**generator** instead of a class. Code **before `yield`** is the setup (`__enter__`),\nthe **yielded value** becomes the `as` target, and code **after `yield`** is the\nteardown (`__exit__`).\n\n```python\nfrom contextlib import contextmanager\n\n@contextmanager\ndef opened(path):\n    f = open(path)          # setup\n    try:\n        yield f             # value bound to 'as'\n    finally:\n        f.close()           # teardown — runs even on error\n\nwith opened(\"data.txt\") as f:\n    print(f.read())\n```\n\nThe `try\u002Ffinally` around the `yield` is essential — without it the teardown is\nskipped when the block raises. Rule of thumb: reach for the decorator for simple,\none-off managers; write a class when you need state across multiple methods.\n",{"id":37,"difficulty":38,"q":39,"a":40},"exceptions-in-exit","hard","How does a context manager handle exceptions in __exit__?","When the `with` block raises, Python passes the exception details into `__exit__`.\nThe crucial part is the **return value**: returning a **truthy** value tells Python\nto **suppress** the exception, while returning `False`\u002F`None` lets it **propagate**\nnormally.\n\n```python\nclass Suppress:\n    def __enter__(self): return self\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        if exc_type is ValueError:\n            print(\"swallowed:\", exc_val)\n            return True          # suppress ValueError\n        return False             # re-raise anything else\n\nwith Suppress():\n    raise ValueError(\"oops\")     # swallowed, program continues\n```\n\n`contextlib.suppress(ValueError)` is the ready-made version of this pattern. Rule\nof thumb: only suppress exceptions you genuinely intend to ignore — accidentally\nreturning a truthy value hides bugs.\n",{"id":42,"difficulty":25,"q":43,"a":44},"multiple-context-managers","How do you use multiple context managers and what are real uses?","You can manage several resources in one `with` by separating them with commas (or\nusing parenthesized form in 3.10+). They are **entered left to right** and\n**exited in reverse order**, so cleanup unwinds correctly.\n\n```python\nwith open(\"in.txt\") as src, open(\"out.txt\", \"w\") as dst:\n    dst.write(src.read())\n# dst closed first, then src\n\nimport threading\nlock = threading.Lock()\nwith lock:                 # acquire on enter, release on exit\n    shared_counter += 1\n```\n\nCommon real uses: **files** (auto-close), **locks** (auto-release even on error),\n**database transactions** (commit\u002Frollback), and temporarily **changing state**\nlike `decimal.localcontext`. Rule of thumb: if you ever write `try\u002Ffinally` to\nrelease something, a context manager expresses it more clearly.\n",null,{"description":11},"Python interview questions on context managers and the with statement, __enter__\u002F__exit__, contextlib.contextmanager, exception handling in __exit__, and multiple context managers.","python\u002Fexceptions\u002Fcontext-managers","Context Managers & with","Errors & Exceptions","exceptions","2026-06-18","_wYx3YKUE7hQadgYFrkMXwIkQXcyoJFa0Pm0YBK9cu8",[55,56,59],{"subtopic":49,"path":21,"order":20},{"subtopic":57,"path":58,"order":12},"try \u002F except \u002F else \u002F finally","\u002Fpython\u002Fexceptions\u002Ftry-except",{"subtopic":60,"path":61,"order":62},"Custom Exceptions & the Hierarchy","\u002Fpython\u002Fexceptions\u002Fcustom-exceptions",3,{"path":64,"title":65},"\u002Fblog\u002Fpython-context-managers-with-explained","Python Context Managers and the with Statement Explained",1781808676561]