JuliaPy / JuliaPy/PyCall.jl

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

Open
#756 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Julia
Stars
1.5k
Forks
186
PR merge metrics
No merged PRs in 30d

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

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.