JuliaPy / JuliaPy/PyCall.jl

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

Ouverte
#756 2 commentaires 0 réactions 0 personnes assignées Voir sur GitHub
Langage dominant
Julia
Étoiles
1.5k
Forks
186
Métriques de merge des PR
Aucune PR mergée en 30 j

Description

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
```

Guide de contribution

Aucun guide de contribution indexé pour ce dépôt

Piste de recherche

Commencez par lire le point d’entrée `pyimport` existant et l’implémentation proposée de `safe_pyimport` dans cette issue. Confirmez le comportement souhaité avec l’exemple `Foo` : l’importation du module Julia réussit lorsque le package Python n’est pas disponible, tandis que l’accès à l’importation échouée déclenche l’erreur enregistrée.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
julia, python
Domaine
tooling
Type d'issue
Fonctionnalité
Difficulté
3/5
Temps estimé
1-2 jours
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
35/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.