The 'do'-keyword when it doesn't create an anonymous function and pass it as the first argument to a function call

Hello there,

I am trying to learn Julia, and I came by the do keyword in a setting that I do not understand. So I am asking for some help to work out what happens here.

HDF5.h5open(fname, "r") do fd
#=
lots of stuff involving fd
=#
end

I can see here that the do keyword makes an anonymous function and pass it as the first argument to the function on the left hand side of the do keyword. But the documentation says that the HDF5.h5open function accepts exactly two arguments, and neither should be a function. So in this case the do-keyword must have some other meaning.

Could you please explain?

Kind regards

It seems more likely that the h5open documentation is incomplete than the do keyword does something undocumented. Based on how the standard open function works, I would expect the above to effectively do

fd = HDF5.h5open(fname, "r")
#=
lots of stuff involving fd
=#
close(fd)

with the twist that the final close(fd) is run also when lots of stuff involving fd is interrupted by an error.

2 Likes
4 Likes

“do” comes from julia itself:

help?> do
search: do Docs download DomainError @doc Cdouble stdout @__dot__ ReadOnlyMemoryError pseudos fieldoffset isreadonly dropdims istaskdone fdio

  do

  Create an anonymous function and pass it as the first argument to a function call. For example:

  map(1:10) do x
      2x
  end

  is equivalent to map(x->2x, 1:10).

  Use multiple arguments like so:

  map(1:10, 11:20) do x, y
      x + y
  end

When you are unsure about something in julia, do not hesitate to use the help by entering ? in a julia REPL.

I would prefer if you don’t quote me partially to completely change the meaning of what I wrote.

2 Likes