Why won't Julia let me put a module import within a function?

I just created the function:

function operats()
    using GLPK
    using Clp
    using JuMP
    using Hungarian
end

and to my surprise this gave me the error:

ERROR: syntax: "using" expression not at top level

The reason I wanted to put that all into a single function was because those are the modules I use for operations research and it would be handy to have a single function that imported them all. May I ask why Julia refuses to allow module imports to appear within a function’s body? Is there a way around it?

Thanks for your time.

you could put the using statements in a file and call

include("thatfile.jl")
3 Likes

You could also write a macro:

macro operats()
    quote
        using GLPK
        using Clp
        using JuMP
        using Hungarian
    end
end

I’m not totally sure the origin of this restriction, but I imagine that it’s part of the general effort to prevent pathological dynamism like the hypothetical:

function import_cor()
     import Statistics: cor
end

function foo()
  cor = 10
  import_cor()
  return cor
end
2 Likes

using modified bindings in the current module scope. If you’re inside a function, you’re not in a module scope. You could define it to operate in the module scope of whatever module encloses the function, but that probably doesn’t do what you want, since you may be calling it from some other module. If you do really want that behavior, you can use eval. As was pointed out, the correct way to factor top-level code is to use include or a macro. @johnmyleswhite is correct of course that the reason we don’t have any sort of dynamic scope for these things is that that would be gratuitous dynamism without any real benefit.

8 Likes

Disallowing it also leaves open the possibility of making it work, i.e. by making those bindings visible only in the local scope.

5 Likes

I actually tried your method of using macros, and I get the exact same error. It seems like Julia doesn’t like using statements in macros either.

Interestingly, copy-pasting your code into the Julia REPL doesn’t give an error, but if you include it in ~/.julia/config/startup.jl there are errors.

EDIT: Oops, not sure why but when I copy-paste your code exactly there’s no error, but when I write the code manually I get the same error as I do for including using in functions.

What code did you write manually?

1 Like

Good question, I’ve found the problem. I called the macros within functions, and that was what caused the error. I’ve since converted those functions into macros. Sorry for forgetting to mention that in my previous post. Thanks for your help, it’s much appreciated!

1 Like