Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Python's 'with' in Julia?

Tags:

julia

Does Julia have an equivalent of Python's with? Maybe as a macro? This is very useful, for example, to automatically close opened files.

like image 781
becko Avatar asked Apr 03 '16 13:04

becko


2 Answers

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.

like image 160
niczky12 Avatar answered Oct 22 '22 06:10

niczky12


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.

like image 22
Seanny123 Avatar answered Oct 22 '22 04:10

Seanny123