NULL PyObject in package

I am creating a package and I have gotten the following error in one of my scripts that is called via include(“script_name.jl”):

ERROR: ArgumentError: ref of NULL PyObject

The error is coming from a usage of np.gradient() within a function.

Oddly this function works perfectly well in a julia notebook, and also I was able to use np.gradient in the package by adding “println(np.gradient([…])” to the start of the script, which printed during compilation of my package.

My issue may have something to do with (Calling the constructor outside a module works, but inside a module throws ArgumentError: ref of NULL PyObject - #2 by Volker) but I don’t know julia well enough to understand the solution provided.

For reference I have the following code at the beginning of the script

using PyCall
np = pyimport("numpy")

I also have these same lines in another script that uses python functions, but this doesn’t seem to be causing an issue.

Also, I tried to find a pure julia equivalent for np.gradient of arrays and there does not seem to be one. Does anyone know if there is such an implementation in julia?

Thank you!

I was able to solve the problem, but I do not understand the solution entirely. In my script I have changed np = pyimport(“numpy”) to

using PyCall

function __init__()
    py"""
    import numpy as np

    def grad(A, dx):
        return np.gradient(A, dx)
    """
end

function test()
    println(py"grad"([1,2,3,4], 0.5))
end

and I get the correct functionality from the test method. Why is it that, when using SciPy I can call “SciPy.interpolate.interp1d” with no issues from within functions of my package, but “np.gradient” is not recognized unless I modify the init method?

If you are using a module, see Using PyCall from Julia Modules