Skip to content

Add close() method and context manager support - #4

Open
IFAKA wants to merge 1 commit into
romanmichaelpaolucci:mainfrom
IFAKA:fix/session-resource-leak
Open

Add close() method and context manager support#4
IFAKA wants to merge 1 commit into
romanmichaelpaolucci:mainfrom
IFAKA:fix/session-resource-leak

Conversation

@IFAKA

@IFAKA IFAKA commented Dec 19, 2025

Copy link
Copy Markdown

Problem

The client creates a requests.Session but provides no way to close it:

self._session = requests.Session()  # Created in __init__
# No close() method or context manager

In long-running applications creating many client instances, this can lead to:

  • Connection pool exhaustion
  • File descriptor leaks
  • Memory growth over time

Fix

Add close() method and context manager support:

def close(self) -> None:
    """Close the underlying HTTP session."""
    self._session.close()

def __enter__(self) -> "Discourses":
    return self

def __exit__(self, exc_type, exc_val, exc_tb) -> None:
    self.close()

Users can now properly clean up resources:

# Option 1: Context manager (recommended)
with Discourses(api_key="key") as client:
    result = client.analyze("text")
# Session automatically closed

# Option 2: Explicit close
client = Discourses(api_key="key")
try:
    result = client.analyze("text")
finally:
    client.close()

Test

Test 1: close() method
  ✓ close() called successfully

Test 2: Context manager
  ✓ Entered context: Discourses(base_url='https://discourses.io/api/v1')
  ✓ Exited context (session closed)

Test 3: Context manager with exception
  ✓ Exception raised, session still closed

Test 4: Session closed state
  ✓ Session closed (adapters before: 2)

==================================================
All tests passed!

Enable proper resource cleanup for the HTTP session:
- close() method to explicitly release connections
- Context manager (__enter__/__exit__) for with-statement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant