Context Informants¶
Context informants tell the ContextManager about the context.
Each informant provides a unique string for each individual context. The context manager then caches objects by context. The context should be destroyed when it is no longer needed.
- class autoinject.informants.ContextVarInformant[source]¶
Context informant for contextvars library.
- class autoinject.informants.ContextVarManager(contextvar_informant: ContextVarInformant, context: Literal['_default', 'same', 'empty', 'copy'] | ContextProtocol | Context | None = '_default', suppress_exit_warning: bool = False)[source]¶
Wrapper around contexts to help manage issues with cleaning up dependencies.
- copy(same_autoinject_context: bool = False)[source]¶
Make a copy of the context, with optional parameter to keep or reset the autoinjection variables.
- static ensure_context_id(context: ContextProtocol | Context | None = None)[source]¶
Ensure there is a context ID.
- static freshen_context(context: ContextProtocol | Context | None = None) Token[source]¶
Refresh the context by resetting the context ID.
- static get_context_id(context: ContextProtocol | Context | None = None) str | None[source]¶
Retrieve the current context ID, but don’t set one if there isn’t one.
- class autoinject.informants.NamedSituationInformant(name: str = 'named_situation')[source]¶
A toy class for demonstrating how contexts work. The context can be changed using
switch_context():from autoinject import injector, NamedContextInformant informant = NamedContextInformant() injector.register_informant(informant) # We are now in the "_default" context informant.switch_context("alpha") # We are now in the "alpha" context
In the above example, any calls to inject classes registered with a cache strategy of
CONTEXT_CACHE(the default) will result in different obtains being returned for the _default context and the alpha context. If the class is registered with a strategy of GLOBAL_CACHE, the same object will be returned.
- class autoinject.informants.SituationInformant(name: str | None = None)[source]¶
Base class for context informants
- Parameters:
name (str) – A unique name for this informant. It will be used to assemble multiple contexts together.
- check_expired_caches()[source]¶
Trigger to check for expired contexts so they can be cleaned-up from memory
- destroy(cache_id: str)[source]¶
Remove all objects cached under the given context.
- Parameters:
cache_id (str) – A value that would have been provided by get_context_id() to the
ContextManager
- class autoinject.informants.ThreadedContextInformant[source]¶
Context informant for threading library