{
    "slug": "py_context_managers",
    "term": "Context Managers & with Statement",
    "category": "python",
    "difficulty": "intermediate",
    "short": "The with statement guarantees __exit__ runs even on exception — used for file handles, locks, transactions, and any resource needing cleanup.",
    "long": "Context managers implement __enter__ (setup, returns the resource) and __exit__ (cleanup, always called) — or use @contextlib.contextmanager with yield. with open('file') as f: closes the file whether the body succeeds or raises. Multiple resources: with open(a) as f, open(b) as g. Custom managers: @contextlib.contextmanager def db_transaction(conn): try: yield conn; conn.commit() except: conn.rollback(). contextlib.suppress(FileNotFoundError) silently ignores specific exceptions. contextlib.ExitStack manages a dynamic number of resources. The PHP equivalent is try/finally blocks or RAII patterns — Python's with is more ergonomic and prevents resource leaks idiomatically.",
    "aliases": [
        "Python with statement",
        "context manager",
        "__enter__ __exit__"
    ],
    "tags": [
        "python",
        "resource-management",
        "patterns"
    ],
    "misconception": "Context managers are only for file handling. Any resource that needs guaranteed cleanup — database connections, locks, network sockets, temporary directories — benefits from a context manager. The with statement guarantees __exit__ is called even if an exception occurs.",
    "why_it_matters": "Context managers (with statements) guarantee cleanup code runs even when exceptions occur — replacing try/finally patterns with a reusable, readable protocol.",
    "common_mistakes": [
        "Not using with for file operations — files are not closed on exception without it.",
        "Not implementing __exit__ to handle exceptions — a context manager that re-raises is fine, but it must return False.",
        "Using contextlib.contextmanager without wrapping the yield in try/finally — cleanup skipped on exception.",
        "Nested with statements instead of a single with statement with multiple context managers."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "py_generators",
        "py_decorators"
    ],
    "prerequisites": [
        "py_generators",
        "py_decorators",
        "exception_handling"
    ],
    "refs": [
        "https://docs.python.org/3/reference/compound_stmts.html#the-with-statement"
    ],
    "bad_code": "# File not closed on exception:\nf = open('data.txt')\ndata = f.read()  # Exception here leaves file open\nf.close()        # Never reached\n\n# Context manager — always closes:\nwith open('data.txt') as f:\n    data = f.read()  # Exception here still closes the file",
    "good_code": "from contextlib import contextmanager\n\n@contextmanager\ndef managed_transaction(conn):\n    try:\n        yield conn\n        conn.commit()\n    except Exception:\n        conn.rollback()\n        raise\n\nwith managed_transaction(db) as conn:\n    conn.execute('INSERT ...')",
    "quick_fix": "Use 'with open(path) as f:' for all file operations — the context manager guarantees the file is closed even if an exception occurs",
    "severity": "medium",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/py_context_managers",
        "html_url": "https://codeclaritylab.com/glossary/py_context_managers",
        "json_url": "https://codeclaritylab.com/glossary/py_context_managers.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Context Managers & with Statement](https://codeclaritylab.com/glossary/py_context_managers) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/py_context_managers"
            }
        }
    }
}