Hi all,
In Mojo there’s no way to introduce a standalone scope - something like C’s bare { ... }. I keep wanting this for two common cases:
- Limiting the visibility of temporaries. In a long function I often compute a bunch of intermediate values (e.g. series coefficients) that are only needed for a few lines. A scope keeps them from leaking into the rest of the function and prevents accidental reuse.
- Controlling destruction timing. A scope forces
vars to be destroyed at a well-defined point rather than at end of function.
The current workarounds all have problems:
if True:- works, but the compiler recognizes the constant condition and emits an “unreachable code” warning. The warning is correct behavior for real code, which makes it a poor idiom for intentional scoping.try: ... finally: pass- compiles and creates a scope, but it’s semantically misleading: readers will reasonably assume error handling is involved. Using an error-handling construct purely for scoping obscures intent.- Nested
def- creates a scope but adds call machinery and capture semantics; overkill.
So: would a bare block statement be a good addition? Something like:
var x = compute_header()
do:
var tmp1 = expensive_intermediate()
var tmp2 = another_intermediate(tmp1)
x = combine(x, tmp2)
# tmp1, tmp2 no longer visible here
Thanks!