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,includebrings everything in the same namespace - Unlike
import,includewon’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.jlcontains the definition and some basic operations of theModuletype, which is the building block of a deep learning modelmodel.jlcontains the definition of theModeltype, which represents a deep learning model. It supports very limited autodiff based on Jacobian matricesmoduledef.jlcontains definitions of severalModules, likeLinear,ReLu,Sigmoidtrain.jlcontains 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 subdirectoryfor 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.