Temporary Files and Their Lifetime

A temporary file can hold intermediate data without committing a result to its long-term path. Define who owns it and when it is cleaned up.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace ownership
  2. Avoid shared test state
  3. Define who owns cleanup before creating the file
  4. Test close and cleanup on the supported platforms

Trace ownership

A report writer can create a unique temporary file, write completed content, and then hand it off to a replacement operation. If writing fails, the caller should know whether the writer cleans that file. A context-managed file lifetime addresses the open handle.

Avoid shared test state

Parallel report tests should not reuse the same temporary name. Use the platform's temporary-file or directory facility and confine fixtures to it. Fresh fixtures keep cleanup from affecting another test.[1]

Define who owns cleanup before creating the file

An export builder can own a temporary file until the output is validated. A validation failure leaves the final output alone and should remove the temporary file according to that design. A complete temporary file may become the final one through replacement. See using a file context manager.

Creation: writer owns temporary resource
Error before commit: discard temporary result
Success: transfer bytes into destination in the intended manner
Ownership after transfer belongs to the published artifact

Test close and cleanup on the supported platforms

Opening and deleting behavior can differ when a temporary handle stays open. Use the platform-aware library primitive for the required lifetime. Test an exception in validation and a consumer accessing the completed file after the writer closes.

References

  1. Python Software Foundation, io: Core Tools for Working with Streams ↩