Skip to content

Instantly share code, notes, and snippets.

@twolfson
Created January 22, 2022 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twolfson/2929dc1163b0a76d2c2b66d51f9bc808 to your computer and use it in GitHub Desktop.
Save twolfson/2929dc1163b0a76d2c2b66d51f9bc808 to your computer and use it in GitHub Desktop.
Add `persist` flag to Python's tempfile.TemporaryDirectory
# https://github.com/python/cpython/blob/v3.10.2/Lib/tempfile.py#L782-L852
class PersistableTemporaryDirectory(tempfile.TemporaryDirectory):
def __init__(self, *args, persist: bool, **kwargs):
self.persist = persist
ret_val = super().__init__(*args, **kwargs)
# If we're persisting, then remove `weakref` binding for cleanup at garbage collection
if self.persist:
self._finalizer.detach()
return ret_val
def __exit__(self, *args, **kwargs):
# If we're not persisting, then perform normal cleanup
if not self.persist:
return super().__exit__(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment