JuliaPy / JuliaPy/PyCall.jl

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

Offen
#756 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
Vorherrschende Sprache
Julia
Sterne
1.5k
Forks
186
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

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

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.