DEV Community

Cover image for Another way of working with temporary files
Jorge Alvarado
Jorge Alvarado

Posted on

Another way of working with temporary files

🗂 tmp-folder allows you to easily use a temporary folder during the execution of a function. After it is done executing, the folder will be automatically deleted (with all its content of course).

Install it

pip install tmp-folder
Enter fullscreen mode Exit fullscreen mode

Watch it in action

All you need to do is to decorate the function that needs a temporary folder and your function will get a free extra parameter, that's your tmp-folder:

# main.py
from pathlib import Path

from tmp_folder import use_tmp_folder


@use_tmp_folder  # This is the decorator
def do_some_stuff(my_tmp_folder: Path) -> Path:
    with open(my_tmp_folder / "some_file.txt", "w") as file:
        file.write("Hello World")

    assert my_tmp_folder.exists()

    return my_tmp_folder


if __name__ == "__main__":
    my_tmp_folder = do_some_stuff()
    assert not my_tmp_folder.exists()
    print("Everything went ok")

Enter fullscreen mode Exit fullscreen mode

We execute the code with python main.py:

Everything went ok
Enter fullscreen mode Exit fullscreen mode

✅ Cool, there are no assertion errors 👏🎉🎉🎉.

Key points:

  • The function that needs temporary stuff, is decorated with use_tmp_folder.
  • You get a new parameter in your decorated function (it can be named however you want, in this case my_tmp_folder). See how when you are calling do_some_stuff, you are not passing any argument, but on its definition there is a parameter, well, that's because tmp-folder adds it for you.
  • This new parameter is the temporary folder that tmp-folder gives you. You can store whatever you want in there. After the decorated function is done executing: bye bye temporary folder 👋.
  • The parameter is a Path object, so you get all the cool things pathlib offers.
  • The decorator is built on top of Python's TemporaryDirectory, so you know is a safe thing to use.

For more details see the package documentation.
Image author.

Top comments (2)

Collapse
 
miguelsmuller profile image
Miguel Müller

I liked knowing this approach

Collapse
 
jalvaradosegura profile image
Jorge Alvarado

Thanks I'm glad you liked it :)