Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add py_import_from() #1465

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ export(py_has_attr)
export(py_help)
export(py_help_handler)
export(py_id)
export(py_import_from)
export(py_install)
export(py_is_null_xptr)
export(py_iterator)
Expand Down
34 changes: 33 additions & 1 deletion R/import.R
Original file line number Diff line number Diff line change
Expand Up @@ -252,5 +252,37 @@ import_from_path_immediate <- function(module, path, convert) {
}



#' Import objects from a Python module
#'
#' @param module string, name of python module
#' @param ... names of objects to import as bare expressions. Can be named to
#' change the binding name in R. rlang dynamic dots are supported.
#' @param .convert passed on to `import()`
#' @param .env R environment where to assign the imported symbols.
#'
#' @details This function is useful for porting the Python idiom `from foo
#' import abc, hjk, xyz` to R. Here are few examples:
#'
#' | Python | R |
#' |---------------------------------------------|--------------------------------------------------|
#' | `from numpy import abs` | `py_import_from("numpy", abs)` |
#' | `from jax import grad, jit, vmap` | `py_import_from("jax", grad, jit, vmap)` |
#' | `from datetime import date as d, time as t` | `py_import_from("datetime", d = date, t = time)` |
#'
#' @return `NULL` invisibly. This function is called for its side effect of
#' assigning symbols in `.env`.
#' @export
py_import_from <- function(module, ..., .convert = TRUE, .env = parent.frame()) {
module <- import(module, convert = .convert)
dots <- lapply(
rlang::ensyms(..., .named = TRUE, .ignore_empty = "all",
.ignore_null = "none", .homonyms = "error",
.unquote_names = TRUE, .check_assign = TRUE),
function(name) {
py_maybe_convert(py_get_attr(module, as.character(name)),
.convert)
})
list2env(dots, envir = .env)
invisible()
}

33 changes: 33 additions & 0 deletions man/py_import_from.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading