Initialization of Packages on import

I’m still getting used to the new v0.7 Pkg (Pkg3), but I kind of wish I had more documentation on it. Overall looks cool, I’m just getting confused about some things.

One specific change I’m struggling with is that it seems like module-level code is only run once, during pre-compilation. During subsequent imports, this code isn’t re-run.

For example, using a package:

module Tester

@info "test"

end

When you first type using Tester, it will appropriately print out “test”. But, then if you quit Julia, restart it, and type using Tester again, it won’t appear again.

If there is initialization code for a package, is there a way to have a segment of code run on the first import during a session? For example, include a startup.jl file in the package directory?

You can have an __init__ function.

:slight_smile: I just saw that looking through someone else’s code. That’s perfect.

Is that documented somewhere? Is the documentation just lagging behind, or is there some big “here’s how the new Pkg works” page that I’m missing? (I’ve obviously read https://docs.julialang.org/en/stable/stdlib/Pkg/)

This is not related to Pkg, __init__has been there for long. But it does not seem to be documented, so that would be good to do! Seems like a great opportunity for you to contribute to Julia! Otherwise, please open an issue and someone else will get to it.

Ahh! That was my issue. I was thinking about it in terms of the Pkg system. The precompilation of modules on import, and the usage of __init__ is very nicely documented here:

https://docs.julialang.org/en/stable/manual/modules/#Module-initialization-and-precompilation-1

That explains a lot. Thanks

1 Like

Nice find, would be good to have it available from the REPL too, see https://github.com/JuliaLang/julia/issues/28730

updating the link since that one is now dead : Modules · The Julia Language