Is "import" required for user-defined modules?

When using modules, is “import” or “using” needed? The reason I ask is that in the following toy example, according to my reading of the documentation, an “import” (or “using”) statement is required. But the program runs whether or not the “import” statement is commented. Why?

And assuming it is not needed, is it bad practice for me to make a habit of not using it?

module ex1mod

using Printf

function printsquare(x)
    @printf("%g^2 = %g\n", x, x^2)
end

end # module ex1mod

#import ex1mod   # not needed!

ex1mod.printsquare(2)

you don’t need it in this case because the module is evaluated in the same scope.

julia> include("test.jl") #without your last line
Main.ex1mod

So ex1mod.printsquare is in fact Main.ex1mod.printsquare.
(include is equivalent to pasting those lines in REPL directly).

You will need it if your ex1mod is an actual package because otherwise Julia will not know what ex1mod is. You can think of import X as finding where / which version of X and then include(X.jl)

1 Like

Thank you. But (at least) 99.9% of all software I have ever written (not just in Julia) has been for personal or internal company/department use. So it seems to me that, for the average user, the advice should be to not worry about using “import” and “using” for loading your own modules, or using “export” inside your modules, unless intending to make it into a package.

On the contrary, since packages are so lightweight and easier to manage as a coherent unit (think: CI, versioning, etc), code should just be organized into packages, even if used internally/locally.

7 Likes