Created
January 22, 2022 01:14
-
-
Save twolfson/2929dc1163b0a76d2c2b66d51f9bc808 to your computer and use it in GitHub Desktop.
Add `persist` flag to Python's tempfile.TemporaryDirectory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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