JuliaPy / JuliaPy/PyCall.jl

Proposal: "safe_pyimport" to delay "module not found" error

Abierto
#756 2 comentarios 0 reacciones 0 asignados Ver en GitHub
Lenguaje dominante
Julia
Estrellas
1.5k
Forks
186
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

I have a proposal for a simple feature that might be useful. It solves the problem that sometimes I want to import a Python package at the Julia module top-level, but I want the module still load-able if the Python package fails to load (the error instead can be delayed to when/if its actually attempted to be used).

```julia
module Foo

function __init__()
global pypkg = pyimport("DoesntExist")
end

foo() = pypkg.stuff(...)

end

using Foo # I want no error here
Foo.foo() # error only comes here when actually trying to use it

```

The reason for this is mostly convenience (to avoid having to write eg `pyimport("numpy")` a million times in each function and instead just have a single `np = pyimport("numpy")` in my module, and makes most sense for Python packages which aren't part of the "core" functionality of your Julia module.

A possible implementation is attached below and is only ~10 lines.

Just wanted to suggest this, let me know if there's any interest for a PR, but also feel totally free to close this without explanation (which I'll take as a very understandable, "not suited for PyCall itself")

```julia
struct FailedPyimport
err
end
getproperty(p::FailedPyimport, ::Symbol) = throw(getfield(p,:err))

@doc doc"""

safe_pyimport(s)

Like `pyimport`, but if `s` fails to import, instead of an error right away, the
error will be thrown the first time the user tries to access the contents of the
module.
"""
function safe_pyimport(s)
try
pyimport(s)
catch err
FailedPyimport(err)
end
end
```

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Línea de trabajo

Start by reading the existing `pyimport` entry point and the proposed `safe_pyimport` implementation in this issue. Confirm the desired behavior with the `Foo` example: importing the Julia module succeeds when the Python package is unavailable, while access to the failed import raises the saved error.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
julia, python
Área
tooling
Tipo de issue
Nueva funcionalidad
Dificultad
3/5
Tiempo estimado
1-2 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.