mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

Scope guard (P1-13): with_scope and ScopeGuard

Mojo has no with statement, but it has something just as strong:

Source: mjdi/docs/scope-guard.md

Mojo has no with statement, but it has something just as strong: structs with a __deinit__ destructor that the compiler must run when the value goes out of scope — including while an error propagates through the frame (verified by tests/test_guards.mojo on the target compiler). That is RAII, and it makes forgetting close_scope() structurally impossible.

with_scope — the function-style guard

from mjdi import with_scope

def handle_request(mut scope: Scope[type_of(reg)]) raises -> String:
    var session = scope.resolve[Session]()
    return session.respond()

var result = with_scope(app, handle_request)
  • container.create_scope() produces the scope (with the container's configured values mirrored into it);
  • handle_request is a thin (capture-free) function taking the scope by mutable reference and returning a Movable result, which with_scope forwards — return String("") when there is nothing to report;
  • close_scope() is guaranteed on normal completion and on every error path: an error raised by the body is re-raised after the scope closed, so cached scoped instances (and their pre_destruct hooks) never leak past the statement.

No hidden copies: the body receives the scope itself by mutable reference; the guard owns it.

ScopeGuard — the ownership guard

For code that cannot use a function-style body, move the scope into a guard:

var scope = app.create_scope()
var guard = ScopeGuard(scope^)

var session = guard.resolve[Session]()   # guarded delegation
guard.close()                             # exactly-once close
  • ScopeGuard owns the scope; resolve, set_value, and has_value delegate to it.
  • close() is idempotent — closing twice is a no-op, and the destructor will not close again.
  • If you never call close(), __deinit__ closes the scope when the guard leaves its lexical scope — on the normal path AND during error unwinding. This is the guarantee the failing-visitor tests pin: tests/test_guards.mojo proves a guard that was never closed explicitly still releases its scope while an error propagates.
  • The guard is deliberately not Movable: moving a resource-owning guard would widen the lexical region in which the resource is alive.
  • Use-after-close is prevented by ownership: the guard owns the scope, and once the guard is gone the scope is gone with it.

Which one to use

Prefer with_scope whenever the work fits a function body — it is one statement and cannot leak. Use ScopeGuard when the scope must live across several statements or the ownership shape is dictated by surrounding code (see templates/service_app for the long-running pattern).