Does Julia have an equivalent of Python's with
? Maybe as a macro? This is very useful, for example, to automatically close opened files.
Use a do
block. Docs on do blocks are here.
And here is an example of how to do the usual with open(filename) as my_file
of Python in Julia:
open("sherlock-holmes.txt") do filehandle
for line in eachline(filehandle)
println(line)
end
end
The above example is from the Julia wikibooks too.
Although the do
block syntax does have certain similarities to Python's with
statement, there is no exact equivalent. This is discussed in further detail in the GitHub issue "with
for deterministic destruction". The issue concludes that this structure should be added to Julia, although no syntax or plan for such is established.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With