Skip to main content
Context managers provide automatic resource creation and cleanup, ensuring resources are properly deleted even if errors occur. This is one of the most powerful features of the OpenShift Python Wrapper.

What Are Context Managers?

Context managers use Python’s with statement to manage resource lifecycle:
  1. Entering: Resource is created/deployed when entering the context
  2. Working: You work with the resource within the context
  3. Exiting: Resource is automatically cleaned up when exiting
This pattern is defined in ocp_resources/resource.py:759 with the __enter__ and __exit__ methods.

Basic Usage

Simple Context Manager

Context Manager with Error Handling

Context Manager Lifecycle

Understanding the exact flow helps you use context managers effectively:

Lifecycle Flow Diagram

Controlling Teardown Behavior

Disable Automatic Cleanup

Custom Cleanup Timeout

Wait for Resource on Entry

By default, __enter__ calls deploy(wait=False). You can change this:

Nested Context Managers

You can nest context managers to manage dependencies:

Multiple Resources (Flat Structure)

For multiple independent resources, use flat structure:

Testing Patterns

Pytest Fixtures with Context Managers

Conditional Cleanup

Environment-Specific Cleanup

Skip Cleanup in Debug Mode

Environment Variable Control

The wrapper supports environment variables for controlling cleanup:

Error Handling in Context Managers

Handle Teardown Errors

Custom Context Manager Class

You can create custom resource classes with specialized cleanup:

Performance Considerations

Parallel Resource Creation

Context managers create resources sequentially. For parallel creation:

Best Practices

Use Context Managers

Always use context managers for temporary resources to ensure cleanup.

Set Appropriate Timeouts

Configure delete_timeout for resources that take time to clean up.

Handle Errors Gracefully

Catch ResourceTeardownError for critical cleanup failures.

Use teardown=False for Persistence

Disable teardown for resources that should outlive the context.

Common Patterns

Pattern 1: Test Setup and Teardown

Pattern 2: Resource Factory

Next Steps

Resource Class

Learn about the base Resource class

Namespaced Resources

Working with namespaced resources

Testing Guide

Best practices for testing with resources

Exceptions

Handle errors and exceptions