Description
Feature or enhancement
If you use tempfile.TemporaryDirectory()
, the directory is automagically deleted, what is the whole purpose of this class. But sometimes you may want to take a look at it for debugging reasons, so it would be nice to have a delete=False
to prevent deleting.
Pitch
Code using this could look like this:
import argparse
import tempfile
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--keep-temp-files", action="store_true", help="Don't delete temporary files")
args = parser.parse_args()
with tempfile.TemporaryDirectory(delete=not args.keep_temp_files) as tempdir:
# Do something
if args.keep_temp_files:
print(f"You can view your temporary files at {tempdir}")
if __name__ == "__main__":
main()
I personal use tempfile.TemporaryDirectory()
a lot, especial in build scripts. Sometimes a need to take a look at the content of these. so having this Option would be great for that.
Other ways to achieve this
Of course, there would be other ways to achieve this.
1. Use a extra function that takes the directory as argument:
if args.keep_temp_files:
do_something("some/other/dir")
else:
with tempfile.TemporaryDirectory() as tempdir:
do_something(tempfile)
This would need some code rewrite.
2. Using input()
with tempfile.TemporaryDirectory() as tempdir:
# Do something
if args.keep_temp_files:
print(f"You can view your temporary files at {tempdir}. Press enter to delete the files.")
breakpoint()
This could cause problems in situations, where you can't easily give some Keyboard input to TTY.
3. Using a custom function
def my_temp_dir(delet: bool = false):
if delete:
return tempfile.TemporaryDirectory()
else:
return my_custom_handler()
This will blow up your code when you just write a simple script. Python also often used by beginners, which may don't know, they can do this and start refactoring their code.
Why you should implement this
The argument can be easy added to exiting scripts if needed, without any additional work. A scripting language like Python should allow this to make debug more easy and more beginner friendly.
It is absolutely no work to implement this. If this would be much work to implement and maintain this, I would not suggested it. But in this case, it's just 3 steeps:
- Take a additional argument in
__init__()
: - Save is as class attribute
- In
__exit__()
ask, if it should delete or not
Previous discussion
None