I often am making types that need a open
/ close
pair, so I usually add a method allowing them to be used in a do
block that automatically clean up after itself. I’m thinking about wrapping this boilerplate into a @doable
macro - is there something like this already out there?
I started out by writing the docstring:
==========================
@doable function myopen(x, y)
# construct `z`. later it should be closed with `Base.close(z)`
end
The @doable
macro adds a method with a Function
first argument. This form
calls the given function and closes the object within a finally
block. So the
above example creates another function of the form:
function myopen(fn::Function, x, y)
obj = myopen(x, y)
try
fn(obj)
finally
close(obj)
end
end
which enables users to write:
myopen(4, 5) do x
# do stuff with x
end