# Current best practices for resource acquizition and cleanup?

**URL:** <https://discourse.julialang.org/t/current-best-practices-for-resource-acquizition-and-cleanup/35509>\
**Category:** General Usage\
**Tags:** scope\
**Created:** [March 4, 2020, 10:16am UTC](https://discourse.julialang.org/t/current-best-practices-for-resource-acquizition-and-cleanup/35509 "2020-03-04T10:16:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![AdamR](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/adamr/32/5109_2.png) [@AdamR](https://discourse.julialang.org/u/AdamR)\
**Post date:** [March 4, 2020, 10:16am UTC](https://discourse.julialang.org/t/current-best-practices-for-resource-acquizition-and-cleanup/35509/1 "2020-03-04T10:16:43Z")

</div>

I took me by surprise that

```julia
    with DBInterface.execute(db, sql) as q
        # do stuff with q
    end

```

does not deterministically finalize (destruct) `q`. After digging deeper (e.g. [https://github.com/JuliaLang/julia/issues/7721](https://github.com/JuliaLang/julia/issues/7721) ) I found out, that up to mid-2019 it is a known problem in the Julia language specification.

There are exactly two walkarounds of this problem. One is to define

```julia
DBInterface.execute(f::Function, args...) = begin
  conn = db_connect(args...)
  try
    f(conn)
  finally
    finalize(conn)
  end
end

```

and use it like this:

```julia
    DBInterface.execute(db, sql) do q
        # do stuff with q
    end

```

and other, low-level solution is

```julia
    q = DBInterface.execute(db, sql)
    try
        # do stuff with q
    finally
        finalize(q)
    end

```

The latter solution is a little tricky, because a slight variation will not work:

```julia
    try q = DBInterface.execute(db, sql)
        # do stuff with q
    finally
        finalize(q) # Error: q is out of scope here!
    end

```

Stefan Karpinski was fond of a special suffix “!” notation:

```julia
    with DBInterface.execute(db, sql)! as q
        # do stuff with q
    end

```

…but that thread is dead for over 6 months.

Did I miss any development on this topic?
