You can employ syntax almost identical to the linked Python example’s in Julia, because Julia’s assignment operator (=) has always behaved much like Python’s new-fangled := in that it returns its right-hand side. e.g.
if (m = match(rx, str)) !== nothing
@show m
end
(That being said, Python currently allows := in more contexts than Julia, e.g. Julia doesn’t allow assignments inside array literals.)
In general, Julia’s standard library typically supports do block syntax for functions that naturally accept function arguments (e.g. map), functions that require resource cleanup (e.g. open), and for cases that the user cannot emulate efficiently/concisely with a sequence of separate calls (e.g. get! on a dictionary).
match seems to fall into none of those categories. Even without putting the assignment into the if, there’s nothing particularly bad about puting m = match(...) on a separate line from if isnothing(m) as far as I can tell.
The most immediate answer to your “why” question is that nobody has tried to make it happen (write a PR, advocate for it, successfully get it merged). If they had, we’d be able to find/cite a PR with reasons for or against. It’s not terribly unlike this idea for replace, though (#24598) — and there you’ll find little excitement and some other concerns.
That case is quite different: replace already accepts a function argument, so the proposal was merely to move it to the first argument to exploit do syntax.
function when_let(body, val)
if val !== nothing
body(val)
end
end
That would be a bit more general, and apply to any function that uses Nothing as a sentinel value:
julia> when_let(match(r"\d+", "a42b")) do m
println(m.match)
end
42
julia> a = collect(11:15);
julia> when_let(findfirst(iseven, a)) do i
println("$i => $(a[i])")
end
2 => 12