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.

1 Like
2 Likes