Hello, everyone. I am asking a question on Julia’s code loading mechanism.
In Python, import some_module
can be used for both importing some package in site packages and loading a module file in the same directory. However, in Julia, import
or using
can only load packages in the registry, but not load source files in the same directory. Julia do provides include
for code loading, but include
has the following drawbacks:
- Unlike
import
,include
brings everything in the same namespace - Unlike
import
,include
won’t check whether the code has been loaded
This causes the “including multiple times” problems. For example, when I am writing code for the CAs of the pattern recognition course, I implemented a deep learning framework in Julia, and these are the source files in the project:
module.jl
contains the definition and some basic operations of theModule
type, which is the building block of a deep learning modelmodel.jl
contains the definition of theModel
type, which represents a deep learning model. It supports very limited autodiff based on Jacobian matricesmoduledef.jl
contains definitions of severalModule
s, likeLinear
,ReLu
,Sigmoid
train.jl
contains the code to initialize and train a model
Both model.jl
and moduledef.jl
include module.jl
for the definition of Module
. And train.jl
includes both model.jl
and moduledef.jl
. Since the include
in Julia behaves just like #include
in C, module.jl
will be included twice. If the functions in those files are in the top level, they are just brought to the top level of train.jl
and defined twice. If all the code are wrapped in a Julia module (say, with the same name of the source file), you will see Main.model.module
and Main.moduledef.module
. They are different Julia modules, but with exactly the same content!
import
/ using
do provide mechanisms to resolve this. However, to use import
or using
, you have to:
- Create a subdiretory with its own
Project.toml
- Place you source in the respective subdirectory
- In you project root, run
] dev subdirectory
for each subdirectory
This is a lot of trouble, especially when the dependency between source files is complicated.
I have read Julia’s official documentation on code loading There’s no example of best practice of a project layout or how to split your code into multiple files.
This really imposes a lot of challenge when you are working with a large Julia project. If Julia supports C like #ifdef
mechanism, or Python like import, or Rust like mod
/ use
, this problem could have been elegantly solved. I have done some STFW, but I haven’t found any solutions.