python-context-management
Design or review synchronous with-blocks and context managers for resource cleanup or temporary state restoration.
Files2
View on GitHubSKILL.mdskills/python-context-management/SKILL.md
GitHubPurpose
Guide the choice and design of synchronous Python context managers for resource lifetime management and temporary state restoration.
Trigger / When to use
Use this skill when:
- Deciding whether to use
with,@contextmanager, or a class-based__enter__/__exit__manager. - Designing a custom context manager that must handle acquisition, cleanup, rollback, or ambient-state restoration.
- Reviewing code that uses manual
close()and deciding ifwithis more appropriate. - Connecting setup or cleanup failures to the existing semantic error model.
- Using
ExitStackfor dynamic or multi-resource cleanup.
Do not use this skill when:
- The resource involves
async with,async for, or cancellation patterns. - The task is generic dependency injection, bootstrap, or runtime orchestration.
- The task is pytest fixture design beyond lifetime discipline compatibility.
- The task is decorator-driven implicit lifetime management (
ContextDecoratordual-use).
Inputs
- The resource or state being managed (file, lock, connection, cwd, env var, etc.).
- Whether acquisition is stateful, multi-step, or failure-prone.
- Whether the resource must be cleaned up on both normal and error paths.
- Whether ambient state must be fully restored after the block.
- Whether the manager may be reused across multiple
withinvocations.
Process
- Lifetime scope — Does the lifetime fit one block and does the object
support the protocol? Default to
with. If the lifetime genuinely crosses function boundaries, allow manualclose()paired withfinally. - Manager form — Is the flow stateless and single-path? Use
@contextmanager. Does it need internal state, multiple cooperating methods, or richer exception translation? Use a class-based manager with__enter__/__exit__. - Acquisition placement — Effectful or failure-prone acquisition belongs
in
__enter__, not__init__.__enter__returns the resource or facade, notselfunless the manager is the resource. - Cleanup and error policy — Do not suppress exceptions by default.
If cleanup fails while a primary error is active, log it and let the
original propagate; do not replace it. Translate known errors with
raise X from Y; propagate unknowns untouched. - Advanced patterns — Use
ExitStackfor dynamic resource sets or partial-acquisition rollback only. Ambient-state managers must restore prior state infinally. Treat instances as one-shot unless reuse is explicit.
Validation
Before proceeding, confirm:
- Resource type known: what is being managed (file, lock, connection, env var, etc.)
- Lifetime scope clear: does the resource lifetime fit a single
withblock, or must it cross function boundaries? - Error model known: does the codebase have a semantic exception hierarchy the manager should translate into?
SOFT FAIL — ask and wait before continuing:
- Resource lifetime scope is unclear (cannot determine if a single
withblock covers it) - Required reuse conflicts with one-shot semantics and cannot be resolved from callers; otherwise default custom manager instances to one-shot
- A required cleanup policy conflicts with the default (propagate the primary failure, never suppress by default); otherwise state and use that default
BLOCKED — stop and redirect:
- Resource involves
async with,async for, or task cancellation → hand off topython-async-await - Task is pytest fixture scope or
ContextDecoratordual-use → hand off to the appropriate skill
Examples
- Positive:
with open(path) as f:— the protocol handlesclose()even on exceptions; no manual cleanup needed. - Negative:
f = open(path)followed bytry: ... finally: f.close()when the lifetime fits a block andwithis supported — the manual pattern adds noise and is error-prone.
Outputs
- Decision:
with,@contextmanager, or class-based manager, with clear rationale. - Correct acquisition, cleanup, and error-handling code.
- Guidance on suppression policy, cause chaining, and cleanup-failure handling.
ExitStackusage when dynamic or multi-resource cleanup is needed.
Boundaries
- Do not cover:
async with/ cancellation, dependency injection / orchestration, pytest fixture design, orContextDecoratordual-use. Hand off to specialized skills instead.
Failure Handling
- Insufficient context: if resource type or lifetime scope cannot be determined, emit SOFT FAIL, state what is missing, and ask before recommending a form.
- Ambiguous error model: if the codebase error model is unknown, recommend the safe default (propagate; no suppression) and note that translation rules may need revisiting once the model is confirmed.
- Out-of-scope pattern detected: if the resource is async or the task is decorator-driven lifetime management, stop immediately and redirect to the appropriate skill rather than producing a partial answer.
Local references
examples.md: detailed positive and negative patterns covering all multi-path decisions —@contextmanagerversus class-based choice, cleanup failure handling, exception suppression,ExitStack, ambient-state restoration, and one-shot behavior.