# PyCall, @pyimport in a function

**URL:** <https://discourse.julialang.org/t/pycall-pyimport-in-a-function/3889>\
**Category:** General Usage\
**Tags:** pycall\
**Created:** [May 23, 2017, 10:22pm UTC](https://discourse.julialang.org/t/pycall-pyimport-in-a-function/3889 "2017-05-23T22:22:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mwsohn](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mwsohn/32/2696_2.png) [@mwsohn](https://discourse.julialang.org/u/mwsohn)\
**Post date:** [May 23, 2017, 10:22pm UTC](https://discourse.julialang.org/t/pycall-pyimport-in-a-function/3889/1 "2017-05-23T22:22:17Z")

</div>

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

```julia
using PyCall
@pyimport xlsxwriter

```

works.

But

```julia
using PyCall

function testxls()
    @pyimport xlsxwriter
end
testxls()

```

ends up with an error message.

Does anyone know what might be the problem here?

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [May 23, 2017, 11:17pm UTC](https://discourse.julialang.org/t/pycall-pyimport-in-a-function/3889/2 "2017-05-23T23:17:16Z")

</div>

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

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

```

---

<div class="post-metadata">

**Author:** ![mwsohn](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mwsohn/32/2696_2.png) [@mwsohn](https://discourse.julialang.org/u/mwsohn)\
**Post date:** [May 24, 2017, 1:02am UTC](https://discourse.julialang.org/t/pycall-pyimport-in-a-function/3889/3 "2017-05-24T01:02:31Z")

</div>

Thank you so much! It works.
