ZContext
API reference for the asynchronous, thread-safe request context manager and state isolation engine.
ZContext provides a robust, thread-safe, and coroutine-aware context storage system built on Python's native contextvars. It manages request-scoped state (such as user identity and restricted fields), ensuring absolute state isolation across concurrent asynchronous task boundaries.
Class Definition & Global Instance
ZCore exposes both the class definition and the pre-initialized global ctx singleton:
from zcore import ctx, ZContext
# or: from zcore.context import ctx, ZContext
class ZContext:
...Strongly-Typed Properties
user_id
Retrieves or sets the authenticated user identifier for the active coroutine context.
# Access
current_id: Any | None = ctx.user_id
# Set (Accepts integer, string, uuid.UUID, or None)
ctx.user_id = 1054
ctx.user_id = "auth0|64f1b2c3"
ctx.user_id = uuid.uuid4()Prop
Type
Polymorphic Identity: As of rc.2, ctx.user_id no longer enforces strict UUID coercion. It supports arbitrary integer, string, or UUID primary keys without raising type errors.
restricted_fields
Accesses or updates the collection of data fields restricted in the current context.
# Access
restrictions: frozenset[str] = ctx.restricted_fields
# Set
ctx.restricted_fields = ["tasks.view.salary", "tasks.create.role"]Prop
Type
The setter converts incoming iterables into an immutable frozenset. This prevents business logic layers from accidentally mutating security restriction rules mid-flight.
Dynamic Key-Value Methods
set
Stores an arbitrary key-value entry in the current execution context store.
ctx.set("tenant_id", "enterprise_01")Prop
Type
get
Retrieves a value from the current execution context.
tenant = ctx.get("tenant_id", default="public")Prop
Type
remove
Deletes a specific entry from the current execution context store.
ctx.remove("tenant_id")Prop
Type
Scoping & Contextvars Lifecycle
scope
Context manager for localized state overrides within a specific code block. Temporarily sets attributes (including properties like user_id) and automatically restores the previous state upon block exit.
# Temporarily act as System User for a specific batch operation
with ctx.scope(user_id=SYSTEM_UUID, tenant_id="system"):
await perform_maintenance_task()
# Context automatically reverts to original user_id and tenant_id hereProp
Type
initialize
Resets the context store to an empty state for the current async task scope. Returns a contextvars.Token used for restoring previous state.
token: Token[Dict[str, Any]] = ctx.initialize()reset
Restores the context store to the state corresponding to the provided token.
ctx.reset(token)