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

Adds py_require() function #1706

Draft
wants to merge 19 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
3576166
Adds py_require() function
edgararuiz Dec 30, 2024
9766d73
Initial work on `get_or_create_venv()`, `uv_binary()`
t-kalinowski Jan 2, 2025
86c4af7
redirect output to file
t-kalinowski Jan 2, 2025
b2f81bf
Restores "replace" to py_require(), and makes both error and regular …
edgararuiz Jan 3, 2025
5577d58
Addresses feedback
edgararuiz Jan 7, 2025
4b24553
Adds exclamation mark to contraint check
edgararuiz Jan 7, 2025
7ef5ad7
Switches to using declared script dependencies
edgararuiz Jan 7, 2025
eff4af3
Removes "replace" and messages, add exclude_newer
edgararuiz Jan 8, 2025
c5708b1
Expands use of set, removes partial matching, simplifies code further
edgararuiz Jan 8, 2025
dac7af7
Renames 'omit' to 'remove', simplifies code further
edgararuiz Jan 9, 2025
d120b16
Makes get_python_reqs() output the default arg values for get_or_crea…
edgararuiz Jan 9, 2025
0273f8f
Switches error output of get_create_venv() based on interactive(), ad…
edgararuiz Jan 9, 2025
59d72af
Adds two more tests, aligns var setting better, adds test reset helpe…
edgararuiz Jan 10, 2025
712b445
initial snapshot tests prototype
t-kalinowski Jan 10, 2025
1d2324d
Switches to using setdiff() for 'remove' action
edgararuiz Jan 10, 2025
b094493
simplify snapshotting approach
t-kalinowski Jan 11, 2025
c7bbc59
support attaching internal namespace in snapshots
t-kalinowski Jan 13, 2025
ef4e2fc
initial "requirements are unsatisfiable" error msg impl.
t-kalinowski Jan 13, 2025
bea217d
Starts adding new tests, defaults get_or_create_venv() args to use wh…
edgararuiz Jan 13, 2025
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
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ S3method(print,python.builtin.list)
S3method(print,python.builtin.module)
S3method(print,python.builtin.object)
S3method(print,python.builtin.tuple)
S3method(print,python_requirements)
S3method(py_str,default)
S3method(py_str,python.builtin.bytearray)
S3method(py_str,python.builtin.dict)
Expand Down Expand Up @@ -190,6 +191,7 @@ export(py_module_available)
export(py_none)
export(py_numpy_available)
export(py_repr)
export(py_require)
export(py_run_file)
export(py_run_string)
export(py_save_object)
Expand Down
10 changes: 10 additions & 0 deletions R/package.R
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@
.globals$suppress_warnings_handlers <- list()
.globals$class_filters <- list()
.globals$py_repl_active <- FALSE
.globals$python_requirements <- structure(
list(
dependencies = character(),
python = NULL
),
class = "python_requirements",
history = list()
)



is_python_initialized <- function() {
!is.null(.globals$py_config)
Expand Down
235 changes: 235 additions & 0 deletions R/py_require.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
#' @export
py_require <- function(packages = NULL,
python_version = NULL,
exclude_newer = NULL,
action = c("add", "remove", "set")) {
action <- match.arg(action)

if (!is.null(exclude_newer) &&
action != "set" &&
!is.null(get_python_reqs("exclude_newer"))
) {
stop(
"`exclude_newer` is already set to '",
get_python_reqs("exclude_newer"),
"', use `action` 'set' to override"
)
}

if (missing(packages) && missing(python_version) && missing(exclude_newer)) {
return(get_python_reqs())
}

req_packages <- get_python_reqs("packages")
if (!is.null(packages)) {
req_packages <- switch(action,
add = unique(c(req_packages, packages)),
remove = setdiff(req_packages, packages),
set = packages
)
}

req_python <- get_python_reqs("python_version")
if (!is.null(python_version)) {
req_python <- switch(action,
add = unique(c(python_version, req_python)),
remove = setdiff(req_python, python_version),
set = python_version
)
}

top_env <- topenv(parent.frame())

pr <- .globals$python_requirements
pr$packages <- req_packages
pr$python_version <- req_python
pr$exclude_newer <- pr$exclude_newer %||% exclude_newer
pr$history <- c(pr$history, list(list(
requested_from = environmentName(top_env),
requested_is_package = isNamespace(top_env),
packages = packages,
python_version = python_version,
exclude_newer = exclude_newer,
action = action
)))
.globals$python_requirements <- pr

invisible()
}

# Print ------------------------------------------------------------------------

#' @export
print.python_requirements <- function(x, ...) {
packages <- x$packages
if (is.null(packages)) {
packages <- "[No packages added yet]"
} else {
packages <- paste0(packages, collapse = ", ")
}
python_version <- x$python_version
if (is.null(python_version)) {
python_version <- "[No version of Python selected yet]"
} else {
python_version <- paste0(python_version, collapse = ", ")
}
cat("------------------ Python requirements ----------------------\n")
cat("Current requirements ----------------------------------------\n")
cat(" Packages:", packages, "\n")
cat(" Python: ", python_version, "\n")
if (!is.null(x$exclude_newer)) {
cat(" Exclude: Updates after", x$exclude_newer, "\n")
}
cat("Non-user requirements ---------------------------------------\n")
reqs <- data.frame()
for (item in x$history) {
if (item$requested_from != "R_GlobalEnv") {
if (item$requested_is_package) {
req_label <- paste0("package:", item$requested_from)
} else {
req_label <- item$requested_from
}
row_x <- data.frame(
requestor = paste(req_label, "|"),
packages = paste(paste0(item$packages, collapse = ", "), "|"),
python = paste(paste0(item$python, collapse = ", "), "|")
)
reqs <- rbind(reqs, row_x)
}
}
if (!is.null(reqs)) {
print(reqs)
}
return(invisible())
}

# Get requirements ---------------------------------------------------------

get_python_reqs <- function(x = NULL) {
pr <- .globals$python_requirements
if (is.null(pr)) {
pr <- structure(
.Data = list(
python_version = c(),
packages = c(),
exclude_newer = NULL,
history = list()
),
class = "python_requirements"
)
pkg_prime <- "numpy"
pr$packages <- pkg_prime
pr$history <- list(list(
requested_from = "reticulate",
requested_is_package = TRUE,
action = "add",
packages = pkg_prime
))
.globals$python_requirements <- pr
}
if (!is.null(x)) {
pr[[x]]
} else {
pr
}
}

# uv ---------------------------------------------------------------------------

uv_binary <- function() {
uv <- Sys.getenv("RETICULATE_UV", NA)
if (!is.na(uv)) {
return(uv)
}

uv <- getOption("reticulate.uv_binary")
if (!is.null(uv)) {
return(uv)
}

uv <- as.character(Sys.which("uv"))
if (uv != "") {
return(uv)
}

uv <- path.expand("~/.local/bin/uv")
if (file.exists(uv)) {
return(uv)
}

uv <- file.path(rappdirs::user_cache_dir("r-reticulate", NULL), "bin", "uv")
if (file.exists(uv)) {
return(uv)
}

if (is_windows()) {

} else if (is_macos() || is_linux()) {
install_uv.sh <- tempfile("install-uv-", fileext = ".sh")
download.file("https://astral.sh/uv/install.sh", install_uv.sh, quiet = TRUE)
Sys.chmod(install_uv.sh, mode = "0755")

dir.create(dirname(uv), showWarnings = FALSE)
# https://github.com/astral-sh/uv/blob/main/docs/configuration/installer.md
system2(install_uv.sh, c("--quiet"), env = c(
"INSTALLER_NO_MODIFY_PATH=1", paste0("UV_INSTALL_DIR=", maybe_shQuote(dirname(uv)))
))
return(uv)
}
}

# TODO: we should pass --cache-dir=file.path(rappdirs::user_cache_dir("r-reticulate"), "uv-cache")
# if we are using a reticulate-managed uv installation.

get_or_create_venv <- function(packages = get_python_reqs("packages"),
python_version = get_python_reqs("python_version"),
exclude_newer = get_python_reqs("exclude_newer")) {
if (length(packages))
packages <- as.vector(rbind("--with", maybe_shQuote(packages)))

if (length(python_version))
python_version <- c("--python", maybe_shQuote(paste0(python_version, collapse = ",")))

if (!is.null(exclude_newer)) {
# todo, accept a POSIXct/lt, format correctly
exclude_newer <- c("--exclude-newer", maybe_shQuote(exclude_newer))
}

input <- "import sys; print(sys.executable);"

result <- suppressWarnings(system2(
uv_binary(), c(
"run",
"--no-project",
"--python-preference=only-managed",
exclude_newer,
python_version,
packages,
"python",
"-c",
shQuote("import sys; print(sys.executable);")
), env = c(
"UV_NO_CONFIG=1"
),
stdout = TRUE,
))
if (!is.null(attr(result, "status"))) {
msg <- c(
"Python requirements could not be satisfied.",
if (!is.null(python_version))
paste0("Python version: ", python_version[2]),
if (!is.null(packages))
# TODO: wrap+indent+un_shQuote python packages
paste0(c("Python dependencies: ", matrix(packages, nrow = 2)[2, ]),
collapse = " "),
if (!is.null(exclude_newer))
paste0("Exclude newer: ", exclude_newer[2]),
"Call `py_require()` to remove or replace conflicting requirements."
)
msg <- paste0(msg, collapse = "\n")
# TODO: check if `stop()` will truncate msg, fix-up hint if yes.
stop(msg)
}

result
}
1 change: 1 addition & 0 deletions reticulate.Rproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
Version: 1.0
ProjectId: 8168e5bb-a24d-416d-b683-1736e171d777

RestoreWorkspace: No
SaveWorkspace: No
Expand Down
98 changes: 98 additions & 0 deletions tests/testthat/_snaps/py_require.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Error requesting conflicting package versions

Code
r_session(attach_namespace = TRUE, {
py_require("numpy<2")
py_require("numpy>=2")
get_or_create_venv()
})
Output
> py_require("numpy<2")
> py_require("numpy>=2")
> get_or_create_venv()
× No solution found when resolving `--with` dependencies:
╰─▶ Because you require numpy<2 and numpy>=2, we can conclude that your
requirements are unsatisfiable.
Error in get_or_create_venv() :
Python requirements could not be satisfied.
Python dependencies: 'numpy<2' 'numpy>=2'
Call `py_require()` to remove or replace conflicting requirements.
Execution halted
------- session end -------
success: false
exit_code: 1

# Error requesting newer package version against an older snapshot

Code
r_session(attach_namespace = TRUE, {
py_require("tensorflow==2.18.*")
py_require(exclude_newer = "2024-10-20")
get_or_create_venv()
})
Output
> py_require("tensorflow==2.18.*")
> py_require(exclude_newer = "2024-10-20")
> get_or_create_venv()
× No solution found when resolving `--with` dependencies:
╰─▶ Because only tensorflow<2.18.dev0 is available and you require
tensorflow>=2.18.dev0, we can conclude that your requirements are
unsatisfiable.

hint: `tensorflow` was requested with a pre-release marker (e.g.,
tensorflow>=2.18.dev0), but pre-releases weren't enabled (try:
`--prerelease=allow`)
Error in get_or_create_venv() :
Python requirements could not be satisfied.
Python dependencies: 'tensorflow==2.18.*'
Exclude newer: 2024-10-20
Call `py_require()` to remove or replace conflicting requirements.
Execution halted
------- session end -------
success: false
exit_code: 1

# Error requesting a package that does not exists

Code
r_session(attach_namespace = TRUE, {
py_require(c("pandas", "numpy", "notexists"))
get_or_create_venv()
})
Output
> py_require(c("pandas", "numpy", "notexists"))
> get_or_create_venv()
× No solution found when resolving `--with` dependencies:
╰─▶ Because notexists was not found in the package registry and you require
notexists, we can conclude that your requirements are unsatisfiable.
Error in get_or_create_venv() :
Python requirements could not be satisfied.
Python dependencies: pandas numpy notexists
Call `py_require()` to remove or replace conflicting requirements.
Execution halted
------- session end -------
success: false
exit_code: 1

# Error requesting conflicting Python versions

Code
r_session(attach_namespace = TRUE, {
py_require(python_version = ">=3.10")
py_require(python_version = "<3.10")
get_or_create_venv()
})
Output
> py_require(python_version = ">=3.10")
> py_require(python_version = "<3.10")
> get_or_create_venv()
error: No interpreter found for Python <3.10, >=3.10 in virtual environments or managed installations
Error in get_or_create_venv() :
Python requirements could not be satisfied.
Python version: '<3.10,>=3.10'
Call `py_require()` to remove or replace conflicting requirements.
Execution halted
------- session end -------
success: false
exit_code: 1

Loading
Loading