Skip to content

Add context manager and close() to ClientBase#121

Open
hownowstephen wants to merge 1 commit intomainfrom
MESS-674_add-context-manager-support
Open

Add context manager and close() to ClientBase#121
hownowstephen wants to merge 1 commit intomainfrom
MESS-674_add-context-manager-support

Conversation

@hownowstephen
Copy link
Copy Markdown
Contributor

@hownowstephen hownowstephen commented May 7, 2026

Summary

  • Adds __enter__, __exit__, and close() to ClientBase
  • Both CustomerIO and APIClient inherit this, enabling:
    with CustomerIO(site_id, api_key) as cio:
        cio.identify(id="123", name="Alice")
    # session is automatically closed, no ResourceWarning
  • close() is also available standalone for non-context-manager usage

Closes #87

Test plan

  • test_context_manager_closes_session — session closed on __exit__, _current_session reset
  • test_close_without_session — calling close() before any request is safe
  • test_close_resets_session — calling close() after requests cleans up properly
  • Full test suite passes (31 tests)
  • Lint passes

Note

Low Risk
Low risk: adds optional lifecycle helpers for HTTP session cleanup without changing request/response behavior. Main risk is unexpected session closure if callers reuse a client after with/close() without re-sending a request to recreate the session.

Overview
Adds context-manager support to ClientBase via __enter__/__exit__ plus a new close() method that closes and clears the pooled _current_session.

Extends unit tests to verify sessions are automatically closed when using with client: ..., that close() is safe before any request, and that close() resets/cleans up an existing session.

Reviewed by Cursor Bugbot for commit 4f51730. Bugbot is set up for automated code reviews on this repo. Configure here.

Allows using CustomerIO and APIClient as context managers to properly
close the underlying requests Session and avoid ResourceWarning for
unclosed SSL sockets.

Closes #87
@hownowstephen hownowstephen mentioned this pull request May 7, 2026
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.

ResourceWarning unclosed ssl.SSLSocket

1 participant