PyCall, @pyimport in a function

I found that @pyimport works well in the global scope but it doesn’t inside a function. For example,

using PyCall
@pyimport xlsxwriter

works.

But

using PyCall

function testxls()
    @pyimport xlsxwriter
end
testxls()

ends up with an error message.

Does anyone know what might be the problem here?

1 Like

@pyimport creates a new Julia module, which you also can’t do inside a function:

julia> function foo()
         module Bar
           x = 1
         end
       end
ERROR: syntax: module expression not at top level

Instead, you can use the pyimport() function, which does not create a Julia module. You’ll just have to access functions and classes with the indexing notation instead of dot notation:

julia> function foo()
         sys = pyimport("sys")
         println(sys[:executable])  # instead of sys.executable
       end
foo (generic function with 1 method)

julia> foo()
/Users/rdeits/.julia/v0.6/Conda/deps/usr/bin/python
2 Likes

Thank you so much! It works.