Skip to content

Add close() and context manager support to Client (#87) - #341

Open
yashbudhia wants to merge 1 commit into
razorpay:masterfrom
yashbudhia:client-close-context-manager
Open

Add close() and context manager support to Client (#87)#341
yashbudhia wants to merge 1 commit into
razorpay:masterfrom
yashbudhia:client-close-context-manager

Conversation

@yashbudhia

Copy link
Copy Markdown

Fixes #87.

Client.__init__ creates a requests.Session() when none is passed in, but nothing ever closes it. In long-running processes, and in any test suite run with warnings enabled, every client that goes out of scope produces ResourceWarning: unclosed <socket.socket ...> as the pooled connections are garbage collected, which is the symptom reported in #87.

Change

  • Client.close() closes the underlying session and releases its pooled connections.

  • Client supports the with statement, so the session is closed on exit even if the block raises:

    with razorpay.Client(auth=(key_id, key_secret)) as client:
        client.payment.fetch(payment_id)
  • A session passed in by the caller is closed by close() as well, matching the behaviour of requests.Session itself. This is documented in the README.

  • Existing code that never closes the client is unaffected.

Tests

tests/test_client_session.py covers close(), the context manager return value, closing on normal exit, closing when the block raises, and the default session being closed. Full suite: 161 passed, 1 skipped.

Docs

README gets a short "close it when you are done" snippet under Usage, and CHANGELOG has an entry under Unreleased.

Client creates a requests.Session on construction and never closed it,
so long-running processes and test suites saw ResourceWarning: unclosed
socket for every client that went out of scope.

Client.close() now closes the session and releases its pooled
connections, and Client supports the with statement, closing the session
on exit even when the block raises. A session passed in by the caller is
closed too, which is documented in the README. Existing code that never
closes the client behaves exactly as before.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011ZJQzxtgWvkWobxsDcuLoW
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 - Requests session is not closed

1 participant