Search code examples
rdecorator

Wrapping functions in R similar to Python decorators


In my project I have a lot of functions to work with database looking like this:

some_function <- function(smth) {
  con <- dbConnect(SQLite(), db)
   -- something -- 
  dbDisconnect(con)
  return(smth)
}

Is there any way to reduce the code and write something like a Python decorator with connection and disconnetion from db?

like this:

@conenct-disconnect
some_funcion <- function(smth){
-- something --
}

Or may be another way to do it?


Solution

  • A function operator

    with_con <- function(f, db) {
      function(...) {
        con <- dbConnect(SQLite(), db)
        f(..., `con` = con)
        on.exit(dbDisconnect(con))
      }
    }
    
    some_func <- function(query, con) {
      #so something with x and the connection
      dbGetQuery(con, query)
    }
    
    
    connected_func <- with_con(some_func, db)
    
    connected_func('SELECT * FROM table')