Welcome to jaraco.context documentation!¶
For Enterprise
Professional support for jaraco.context is available as part of the Tidelift Subscription. Tidelift gives software development teams a single source for purchasing and maintaining their software, with professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools.
- class jaraco.context.ExceptionTrap(exceptions: tuple[type[BaseException], ...] = (Exception,))¶
Bases:
objectA context manager that will catch certain exceptions and provide an indication they occurred.
>>> with ExceptionTrap() as trap: ... raise Exception() >>> bool(trap) True
>>> with ExceptionTrap() as trap: ... pass >>> bool(trap) False
>>> with ExceptionTrap(ValueError) as trap: ... raise ValueError("1 + 1 is not 3") >>> bool(trap) True >>> trap.value ValueError('1 + 1 is not 3') >>> trap.tb <traceback object at ...>
>>> with ExceptionTrap(ValueError) as trap: ... raise Exception() Traceback (most recent call last): ... Exception
>>> bool(trap) False
- exc_info: OptExcInfo = (None, None, None)¶
- passes(func: Callable[_P, _R]) functools._Wrapped[_P, _R, _P, bool]¶
Wrap func and replace the result with the truth value of the trap (True if no exception).
Decorate a function that always fails.
>>> @ExceptionTrap(ValueError).passes ... def fail(): ... raise ValueError('failed')
>>> fail() False
- raises(func: Callable[_P, _R], *, _test: Callable[[ExceptionTrap], bool] = bool) functools._Wrapped[_P, _R, _P, bool]¶
Wrap func and replace the result with the truth value of the trap (True if an exception occurred).
Decorate a function that always fails.
>>> @ExceptionTrap(ValueError).raises ... def fail(): ... raise ValueError('failed') >>> fail() True
- property tb: TracebackType | None¶
- property type: type[BaseException] | None¶
- property value: BaseException | None¶
- class jaraco.context.on_interrupt(action: Literal['ignore', 'suppress', 'error'] = 'error', /, code: int = 1)¶
Bases:
ContextDecoratorReplace a KeyboardInterrupt with SystemExit(1).
Useful in conjunction with console entry point functions.
>>> def do_interrupt(): ... raise KeyboardInterrupt() >>> on_interrupt('error')(do_interrupt)() Traceback (most recent call last): ... SystemExit: 1 >>> on_interrupt('error', code=255)(do_interrupt)() Traceback (most recent call last): ... SystemExit: 255 >>> on_interrupt('suppress')(do_interrupt)() >>> with __import__('pytest').raises(KeyboardInterrupt): ... on_interrupt('ignore')(do_interrupt)()
- jaraco.context.pushd(dir: StrPath) Iterator[StrPath]¶
>>> tmp_path = getfixture('tmp_path') >>> with pushd(tmp_path): ... assert os.getcwd() == os.fspath(tmp_path) >>> assert os.getcwd() != os.fspath(tmp_path)
- jaraco.context.remove_readonly(func: Callable[[_FileDescriptorOrPathT], object], path: _FileDescriptorOrPathT, exc_info: tuple[object, OSError, object]) None¶
Add support for removing read-only files on Windows.
- jaraco.context.repo_context(url: str, branch: str | None = None, quiet: bool = True, dest_ctx: Callable[[], AbstractContextManager[str]] = robust_temp_dir) Generator[str]¶
Check out the repo indicated by url.
If dest_ctx is supplied, it should be a context manager to yield the target directory for the check out.
>>> getfixture('ensure_git') >>> getfixture('needs_internet') >>> repo = repo_context('https://github.com/jaraco/jaraco.context') >>> with repo as dest: ... listing = os.listdir(dest) >>> 'README.rst' in listing True
- jaraco.context.robust_temp_dir(*, remover: Callable[[str], object] = <function rmtree>) Generator[str]¶
Create a temporary directory context. Pass a custom remover to override the removal behavior.
>>> import pathlib >>> with temp_dir() as the_dir: ... assert os.path.isdir(the_dir) >>> assert not os.path.exists(the_dir)
- class jaraco.context.suppress(*exceptions)¶
Bases:
suppress,ContextDecoratorA version of contextlib.suppress with decorator support.
>>> @suppress(KeyError) ... def key_error(): ... {}[''] >>> key_error()
- jaraco.context.tarball(url: str, target_dir: StrPath | None = None) Iterator[StrPath]¶
Get a URL to a tarball, download, extract, yield, then clean up.
Assumes everything in the tarball is prefixed with a common directory. That common path is stripped and the contents are extracted to
target_dir, similar to passing-C {target} --strip-components 1to thetarcommand.Uses the streaming protocol to extract the contents from a stream in a single pass without loading the whole file into memory.
>>> import urllib.request >>> url = getfixture('tarfile_served') >>> target = getfixture('tmp_path') / 'out' >>> tb = tarball(url, target_dir=target) >>> import pathlib >>> with tb as extracted: ... contents = pathlib.Path(extracted, 'contents.txt').read_text(encoding='utf-8') >>> assert not os.path.exists(extracted)
If the target is not specified, contents are extracted to a directory relative to the current working directory named after the name of the file as extracted from the URL.
>>> target = getfixture('tmp_path') >>> with pushd(target), tarball(url): ... target.joinpath('served').is_dir() True
- jaraco.context.tarball_cwd(*args: _P.args, **kwargs: _P.kwargs) Generator[_T2_co]¶
A tarball context with the current working directory pointing to the contents.
- jaraco.context.temp_dir(remover: Callable[[str], object] = shutil.rmtree) Generator[str]¶
Create a temporary directory context. Pass a custom remover to override the removal behavior.
>>> import pathlib >>> with temp_dir() as the_dir: ... assert os.path.isdir(the_dir) >>> assert not os.path.exists(the_dir)