'Reticulate fails automatic configuration in R package

I'm working on a R package, that makes use of reticulate to call some functions of a Python package I implemented, installable through pip.

Following its documentation, I setup the reticulate automatic configuration of Python dependencies as follows, in the DESCRIPTION file of my package:

Config/reticulate:
  list(
    packages = list(
      list(package="my_python_package", pip=TRUE)
    )
  )

where my_python_package is the Python package I need to use.

If I install the package locally, where I have the required Python package already installed, everything works fine.
However, if I try to install and use the R package in an environment without the Python package already installed, I get the following error:

Error in py_module_import(module, convert = convert) : 
  ModuleNotFoundError: No module named 'my_python_package'

Detailed traceback:
  File "/home/runner/work/_temp/Library/reticulate/python/rpytools/loader.py", line 39, in _import_hook
    module = _import(

as if reticulate is not able to configure correctly the environment.

Also, the Python package should not be the problem, since when it is installed, I am able to import it and use its functions with no errors.

From the reticulate documentation it seems Config/reticulate: ... is all is needed, but maybe I am missing something.



Solution 1:[1]

I noticed this issue https://github.com/rstudio/reticulate/issues/997 on the reticulate GitHub repository. Apparently, the automatic configuration through Config/reticulate only works if a conda environment is already loaded.

Therefore, I think the only way to configure the correct environment is on the .onLoad function:

  • check if Anaconda is installed, otherwhise launch the Miniconda installation through reticulate::install_miniconda()
  • check if the environment is already present, otherwise create create it through reticulate::conda_create(envname),
  • install the Python dependencies if necessary through reticulate::conda_install(envname, packages),
  • load the configured environment.

In this way, the first time the package is loaded, the environment will be correctly created.
After that, the environment will be automatically loaded.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 elenabusca