jaraco.context
jaraco.context is a Python library providing useful decorators and context managers for common programming patterns. It offers tools like `ExceptionTrap` for exception handling, `pushd` for temporary directory changes, `tarball` for extracting archives, and `temp_dir` for managing temporary file system resources. The current version is 6.1.2, and it maintains an active release schedule with several updates in the past year.
Warnings
- deprecated The `null` context manager, which provides a no-op context, has been deprecated. While still available, users should consider refactoring to avoid its use or using `contextlib.nullcontext` for newer Python versions (3.7+) as an alternative if truly needed for symmetry.
- gotcha When using the `tarball` context manager, a conditional dependency on `backports.tarfile` exists for Python versions prior to 3.12. If you target Python 3.10 or 3.11 and use `tarball`, ensure `backports-tarfile` is installed.
- gotcha Older versions of `jaraco.context` (prior to unspecified fixes) had a vulnerability related to handling certain archive file paths in `tarball`, which could lead to directory traversal and overwriting files outside the intended extraction directory.
Install
-
pip install jaraco-context
Imports
- ExceptionTrap
from jaraco.context import ExceptionTrap
- pushd
from jaraco.context import pushd
- temp_dir
from jaraco.context import temp_dir
- tarball
from jaraco.context import tarball
- on_interrupt
from jaraco.context import on_interrupt
- suppress
from jaraco.context import suppress
- null
from jaraco.context import null
Quickstart
import os
from jaraco.context import temp_dir, pushd
with temp_dir() as tmp_dir_path:
print(f"Temporary directory created at: {tmp_dir_path}")
assert os.path.isdir(tmp_dir_path)
# The temporary directory is automatically removed here
assert not os.path.exists(tmp_dir_path)
# Example with pushd
current_cwd = os.getcwd()
with temp_dir() as tmp_path_for_pushd:
with pushd(tmp_path_for_pushd):
print(f"Current working directory changed to: {os.getcwd()}")
assert os.getcwd() == os.fspath(tmp_path_for_pushd)
print(f"Current working directory restored to: {os.getcwd()}")
assert os.getcwd() == current_cwd