Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

julia: recommended way to `include` files: list of includes in top-level file or nested includes?

What is the recommended way to include all the files for your project?

I have seen many examples that use a similar structure: an ordered list of include statements in a single top-level file (the file that defines a Module, or the "main" file in an application).

This also seemed to be the conclusion in the following thread: https://discourse.julialang.org/t/best-practices-for-structuring-larger-projects/2652?u=nhdaly


However, Lint.jl seems to be very unhappy with this sort of project structure, complaining about the persistent use of undeclared symbols.

Consider the following example:

# --- src/lib1.jl ---
struct MyStruct
    x::Int32
end

# --- src/lib2.jl ---
foo() = MyStruct(3)    # Lint.jl says: E321 MyStruct: use of undeclared symbol

# --- src/MyPackage.jl ---
module MyPackage

include("lib1.jl")
include("lib2.jl")

foo()

end

Of course, this code will work correctly, because MyStruct will be available before lib2.jl is compiled. But Lint.jl cannot know that. Even when using the Atom-integrated linter, it shows the same error.

So is it preferable to have lib2.jl include("lib1.jl") instead of all the includes in the top file? Or is it best to put them in both places, as you might for C++ headers? I haven't seen a definitive recommendation for this anywhere, and I'd love if someone could provide one! :)


EDIT: changed file names to reflect a more typical julia directory structure.

like image 745
NHDaly Avatar asked Apr 29 '18 05:04

NHDaly


People also ask

What does Julia include?

include is used for including the content of a file into your current program. It has per se nothing to do with modules or namespaces.

What is the difference between import and using in Julia?

My guess based on reading the docs: using is used to bring another module into the name-space of the current module. import is used to bring specific types/functions/variables from other modules into the name-space of the current module.

What are modules in Julia?

Modules in Julia are separate variable workspaces, i.e. they introduce a new global scope. They are delimited syntactically, inside module Name ... end . Modules allow you to create top-level definitions (aka global variables) without worrying about name conflicts when your code is used together with somebody else's.


1 Answers

I usually do a:

PkgDev.generate("MyPackage", "MIT")

This generates the whole folder structure. I put my Julia(.jl) files in the src folder and use 'using' to import functions in other Julia files in the same folder.

like image 146
Subhankar Ghosh Avatar answered Sep 25 '22 15:09

Subhankar Ghosh