# Macro for \`do\` block boilerplate?

**URL:** <https://discourse.julialang.org/t/macro-for-do-block-boilerplate/15847>\
**Category:** General Usage\
**Tags:** metaprogramming\
**Created:** [October 3, 2018, 9:32pm UTC](https://discourse.julialang.org/t/macro-for-do-block-boilerplate/15847 "2018-10-03T21:32:23Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ssfrr](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ssfrr/32/3736_2.png) [@ssfrr](https://discourse.julialang.org/u/ssfrr)\
**Post date:** [October 3, 2018, 9:32pm UTC](https://discourse.julialang.org/t/macro-for-do-block-boilerplate/15847/1 "2018-10-03T21:32:23Z")

</div>

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:

```julia
function myopen(fn::Function, x, y)
    obj = myopen(x, y)
    try
        fn(obj)
    finally
        close(obj)
    end
end

```

which enables users to write:

```julia
myopen(4, 5) do x
    # do stuff with x
end

```
