backports-tempfile
This package provides backports of new features found in Python's standard `tempfile` module, primarily `tempfile.TemporaryDirectory` (introduced in Python 3.4), allowing its use in older Python environments, including Python 2.7, 3.4, 3.5, and 3.6. It is currently at version 1.0, with its last release in October 2017, indicating a very slow or ceased release cadence given its backport nature and the progression of Python versions.
Warnings
- gotcha This package primarily backports `TemporaryDirectory` which became standard in Python 3.4. If you are targeting Python 3.4 or newer, this backport is generally not needed, and you should use the native `tempfile` module directly.
- gotcha The package has not been updated since October 2017. This means it only backports features up to Python 3.6's `tempfile` module. Newer features introduced in the standard `tempfile` module (e.g., `delete_on_close` for `NamedTemporaryFile` in Python 3.12, or `errors` parameter for `TemporaryFile` in 3.8) are not included.
- gotcha As with any backport, using `backports.tempfile` in an environment where the native `tempfile` module is already sufficient can introduce unnecessary dependencies and potential confusion, especially if subtle behavioral differences exist or if code paths are not explicitly managed for different Python versions.
Install
-
pip install backports-tempfile
Imports
- TemporaryDirectory
from backports import tempfile # Then use tempfile.TemporaryDirectory
Quickstart
from backports import tempfile
import os
# Create a temporary directory using the backported feature
with tempfile.TemporaryDirectory() as temp_dir:
print(f"Created temporary directory: {temp_dir}")
# Example: create a file inside the temporary directory
file_path = os.path.join(temp_dir, "my_temp_file.txt")
with open(file_path, "w") as f:
f.write("Hello from tempfile backport!")
print(f"File created at: {file_path}")
print(f"Contents of {file_path}: {open(file_path).read()}")
# At this point, temp_dir and its contents should be automatically removed