Skip to content

Commit

Permalink
pythongh-126639: Add ResourceWarning to NamedTemporaryFile
Browse files Browse the repository at this point in the history
  • Loading branch information
graingert committed Nov 11, 2024
1 parent 6ee542d commit 600ffe1
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions Lib/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,11 +437,19 @@ class _TemporaryFileCloser:
cleanup_called = False
close_called = False

def __init__(self, file, name, delete=True, delete_on_close=True):
def __init__(
self,
file,
name,
delete=True,
delete_on_close=True,
warn_message="Implicitly cleaning up unknown file",
):
self.file = file
self.name = name
self.delete = delete
self.delete_on_close = delete_on_close
self.warn_message = warn_message

def cleanup(self, windows=(_os.name == 'nt'), unlink=_os.unlink):
if not self.cleanup_called:
Expand Down Expand Up @@ -469,7 +477,10 @@ def close(self):
self.cleanup()

def __del__(self):
close_called = self.close_called
self.cleanup()
if not close_called:
_warnings.warn(self.warn_message, ResourceWarning)


class _TemporaryFileWrapper:
Expand All @@ -483,8 +494,17 @@ class _TemporaryFileWrapper:
def __init__(self, file, name, delete=True, delete_on_close=True):
self.file = file
self.name = name
self._closer = _TemporaryFileCloser(file, name, delete,
delete_on_close)
self._closer = _TemporaryFileCloser(
file,
name,
delete,
delete_on_close,
warn_message="Implicitly cleaning up {self!r}",
)

def __repr__(self):
file = self.__dict__['file']
return f"<{type(self).__name__} {file=}>"

def __getattr__(self, name):
# Attribute lookups are delegated to the underlying file
Expand Down

0 comments on commit 600ffe1

Please sign in to comment.