R 中的包装函数类似于 Python 装饰器

Wrapping functions in R similar to Python decorators

在我的项目中,我有很多函数可以处理数据库,如下所示:

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

有没有什么方法可以减少代码并编写类似 Python 装饰器的东西,从 db 连接和断开连接?

像这样:

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

或者可能是另一种方法?

函数运算符

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')