Skip to content

Fix ResourceWarning from unclosed file handles#1362

Open
rdcrampton wants to merge 2 commits into
jsvine:developfrom
rdcrampton:fix/close-file-handles
Open

Fix ResourceWarning from unclosed file handles#1362
rdcrampton wants to merge 2 commits into
jsvine:developfrom
rdcrampton:fix/close-file-handles

Conversation

@rdcrampton

Copy link
Copy Markdown

Summary

When pdfplumber.open() is called with a file path (not a stream), it opens an internal file handle. If the user doesn't use a with statement or call close(), that handle leaks until garbage collection, causing a ResourceWarning in Python 3.11+.

This adds a __del__ method to the PDF class that closes internally-opened file handles as a safety net. External streams (passed by the caller) are never closed by the destructor, matching the existing behavior in close().

Changes

  • pdfplumber/pdf.py: Added __del__ method that defensively closes internal file handles on garbage collection. Uses getattr(self, "stream_is_external", True) to safely handle partially-initialized objects.
  • tests/test_resource_warning.py: New test file verifying no ResourceWarning is emitted with context manager usage, destructor cleanup, and that external streams are left open.
  • tests/test_mcids.py: Wrapped pdfplumber.open() in with to fix leaked file handle.
  • tests/test_utils.py: Added missing self.pdf_scotus.close() in teardown_class.
  • CHANGELOG.md: Added entry under Unreleased.
  • README.md: Added to contributors list.

Test plan

  • python -W all -m pytest passes with no ResourceWarning from pdfplumber
  • All 174 existing tests continue to pass
  • New tests verify: context manager path clean, destructor path clean, external streams not closed
  • make lint passes (black, isort, flake8, mypy --strict)

Closes #1336

Add __del__ to PDF class to close internally-opened file handles when
the object is garbage collected without an explicit close() call. This
prevents ResourceWarning in Python 3.11+ when users don't use the
context manager pattern.

Also fix tests that were not properly closing PDF handles.

Closes jsvine#1336
Update __del__ to emit ResourceWarning before closing, matching
Python stdlib behavior (io.FileIO, zipfile.ZipFile). This actively
nudges users toward context managers rather than silently cleaning up.

Also adds docstring to open() promoting the context manager pattern,
and updates tests to verify the warning is emitted when close() is
forgotten but not when using 'with' or explicit close().

Addresses feedback from jsvine#1336.
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