{
    "slug": "py_context_manager_advanced",
    "term": "Advanced Context Managers",
    "category": "python",
    "difficulty": "intermediate",
    "short": "Context managers (with statements) manage resource acquisition and release — contextlib provides tools for creating them without a full class definition.",
    "long": "Context managers implement __enter__ and __exit__. contextlib.contextmanager turns a generator function into a context manager — yield once, cleanup after yield runs on exit. contextlib.suppress suppresses specific exceptions. contextlib.ExitStack dynamically composes multiple context managers. contextlib.asynccontextmanager for async with. Use for: database connections, file handles, locks, temporary directories, mocking, and any resource that needs guaranteed cleanup regardless of exceptions.",
    "aliases": [
        "contextmanager",
        "with statement",
        "contextlib",
        "__enter__ __exit__"
    ],
    "tags": [
        "python",
        "patterns",
        "resource-management"
    ],
    "misconception": "Context managers are only for file handling — they are the correct pattern for any resource requiring guaranteed cleanup: DB connections, locks, HTTP sessions, temp files, and test mocking.",
    "why_it_matters": "Resources without guaranteed cleanup (DB connections not closed on exception, locks not released on crash) cause resource leaks that accumulate until the service fails.",
    "common_mistakes": [
        "Not using a context manager for database connections — connections leak if an exception occurs before close().",
        "contextmanager generator that yields more than once — raises RuntimeError; yield exactly once.",
        "Not using contextlib.suppress for expected exceptions — try/except/pass where suppress is cleaner.",
        "ExitStack not used when the number of context managers is dynamic — manual nesting becomes unmanageable."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "py_error_handling",
        "py_generators",
        "py_testing_pytest"
    ],
    "prerequisites": [
        "py_context_managers",
        "py_generators",
        "py_error_handling"
    ],
    "refs": [
        "https://docs.python.org/3/library/contextlib.html"
    ],
    "bad_code": "# Resource leak on exception:\ndef process_file(path):\n    f = open(path)\n    data = f.read()    # Exception here?\n    f.close()          # Never reached — file handle leaked\n    return data",
    "good_code": "from contextlib import contextmanager, suppress\n\n# Generator-based context manager:\n@contextmanager\ndef db_transaction(conn):\n    try:\n        yield conn\n        conn.commit()\n    except Exception:\n        conn.rollback()\n        raise\n    finally:\n        conn.close()  # Always runs\n\n# Usage:\nwith db_transaction(get_connection()) as conn:\n    conn.execute('INSERT INTO orders ...')\n\n# Suppress specific exceptions:\nwith suppress(FileNotFoundError):\n    os.unlink('/tmp/lock_file')  # OK if already gone",
    "quick_fix": "Use contextlib.ExitStack for managing dynamic numbers of context managers; use contextlib.suppress(ExceptionType) as a clean way to ignore specific exceptions",
    "severity": "low",
    "effort": "medium",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/py_context_manager_advanced",
        "html_url": "https://codeclaritylab.com/glossary/py_context_manager_advanced",
        "json_url": "https://codeclaritylab.com/glossary/py_context_manager_advanced.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": "[Advanced Context Managers](https://codeclaritylab.com/glossary/py_context_manager_advanced) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/py_context_manager_advanced"
            }
        }
    }
}