JuliaPy / JuliaPy/PyCall.jl

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

Aperta
#756 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub
Lingua principale
Julia
Stelle
1.5k
Fork
186
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Descrizione

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

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.