How can I structure a project in multiple modules and have code run in them?

bertulli
Tue, 13 Jun 2023 15:16:00 +0000
General Usage

Hi all! Sorry this is probably noobish but I couldn’t figure it out easily from the docs/Google.
I’m developing a small project for my thesis. I generated a project structure (src/, Project.toml and Manifest.toml), and have some code inside src/. Until now, I manually loaded and executed code when starting my work session, but now I decided to better organize my code. I was advised to use modules, so I activated my project and added the dependencies, but now I couldn’t understand how to achieve what I need.

For context, the project is called ARMCortexM4Model, but the file ARMCortexM4Model.jl contains no real code, all the work is done in other files. For instance, I have created a module named Utils in src/Utils.jl containing some helper functions I need in other scripts.

1. Right now, to use it I need first to

include("Utils.jl")
using .Utils

IIUC I should do something like ] dev Utils to make Julia aware of the submodule, but I can’t:

(@v1.9) pkg> activate .
  Activating project at `~/onedrive/tesi/Julia_package/ARMCortexM4Model`

(ARMCortexM4Model) pkg> dev Utils
    Updating registry at `~/.julia/registries/General.toml`
ERROR: The following package names could not be resolved:
 * Utils (not found in project, manifest or registry)
   Suggestions: IOUtils GRUtils MLUtils PkgUtils EHTUtils DCAUtils pciutils_jll

(ARMCortexM4Model) pkg> dev .Utils
ERROR: Unable to parse `.Utils` as a package.

My guess is that Julia doesn’t know there are submodules, nor where they are, since they do not appear in the Project.toml. Do I have to edit that? How can I split code in different files otherwise? (and btw, is this even the idiomatic way to proceed?)

2. I want to use modules also to run some initialization code at start, but just once (a-là #pragma once in C/C++). For example, I need to read a large CSV file, and store it in a DataFrame. I so put the loading statement in another module, Constants.jl. The idea is to start each “working” script with using Constants and have the DataFrame loaded the first time I execute it, but not subsequent times. Can this be accomplished with modules, maybe, IIUC, using the __init__ functions?

Thanks!

11 posts - 3 participants