thread_context¶
Thread-local context stack support.
This module provides a mechanism to keep per-thread context objects: a Context object pushes an object onto a thread-local stack when entered, and pops it when exited, so that each thread can have its own current context - identified by name - at any time.
Example
from py_misc_utils import thread_context as ptc
with ptc.Context('job', 'render-task') as job:
assert ptc.get_context('job') == 'render-task'
assert ptc.get_context('job') is None
Context
¶
A thread-local context manager.
Entering a Context pushes its object onto a thread-local stack, while exiting pops it back. The top-of-stack object of a named context can be retrieved with get_context().
The same object can be shared by multiple threads, each of them having its own stack.
Source code in py_misc_utils/thread_context.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | |
get_context(name)
¶
Returns the current object of a named context, for the calling thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
The name identifying the context stack. |
required |
Returns:
| Type | Description |
|---|---|
|
The object pushed by the innermost Context being executed by the |
|
|
calling thread, or None if no such context is active. |
Source code in py_misc_utils/thread_context.py
67 68 69 70 71 72 73 74 75 76 77 78 79 | |