snakeoil.contexts module

Various with-statement context utilities.

class snakeoil.contexts.GitStash(path, pathspecs=None, staged=False)[source]

Bases: AbstractContextManager

Context manager for stashing untracked or modified/uncommitted files.

class snakeoil.contexts.Namespace(mount=False, uts=True, ipc=False, net=False, pid=False, user=False, hostname=None)[source]

Bases: SplitExec

Context manager that provides Linux namespace support.

class snakeoil.contexts.SplitExec[source]

Bases: object

Context manager separating code execution across parent/child processes.

This is done by forking and doing some magic on the stack so the contents of the context are executed only on the forked child. Exceptions are pickled and passed back to the parent.

exception ParentException[source]

Bases: Exception

Exception used to detect when the child terminates.

snakeoil.contexts.chdir(path)[source]

Context manager that changes the current working directory.

On exiting the context, the current working directory is switched back to its original value.

Parameters:

path – The directory path to change the working directory to.

snakeoil.contexts.os_environ(*remove, **update)[source]

Mangle the os.environ dictionary and revert on exit.

Parameters:
  • remove – variables to remove

  • update – variable -> value mapping to add or alter

snakeoil.contexts.patch(target, new)[source]

Simplified module monkey patching via context manager.

Parameters:
  • target – Target class or object.

  • new – Object or value to replace the target with.

snakeoil.contexts.syspath(path: str, condition: bool = True, position: int = 0)[source]

Context manager that mangles sys.path and then reverts on exit.

Parameters:
  • path – The directory path to add to sys.path.

  • condition – Optional boolean that decides whether sys.path is mangled or not, defaults to being enabled.

  • position – Optional integer that is the place where the path is inserted in sys.path, defaults to prepending.