Help with modules and types

I am trying organize a simple module and submodules to learn Julia.

I made an HR module, with a submodule, Staff. Inside it, will have a age function, that has a Person as argument.
the model in it first worked well with struct in same module, the Person struct.
Now I wanna create a Model module, separated, to share it with others submodules, as necessary.

So, will be something like:
HR → include Model, Staff
HR → Model → struct Person
HR → Staff → function age(p::Person)

but this dont works… age cant see Person correctly…

How can use Person from submodule Model and in any submodule?

Thanks!!!

Hi @cesarmarinhorj ! How about something like this (I’ve assumed each module is in a separate script)

In HR.jl

module HR

include("Model.jl")
using .Model  # . means look in local scope rather than registry

include("Staff.jl")
using .Staff

end # module

In Model.jl

module Model

struct Person
    age::Int
end

end # module

In Staff.jl

module Staff

using ..Model # .. means look in scope of parent module

function age(p::Model.Person)
    return p.age
end

end # module

Alternatively Person could be exported from Model and then you could just use Person in Staff.

1 Like

Thanks!!! gonna try now!!!
8)

Works!!! thanks too much!!!
8)

1 Like

Great, you’re welcome!

As another point of reference, here is a great example of code written with submodules for a simple microservice:

2 Likes

Note that excessive use of submodules is sort of an anti-pattern in Julia (modules do not play the same role as they do in Python, for example).

Packages are generally “flat”, meaning having a single module and just “including” pieces of code, once, at the top of the module code. Something like:

module MyPackage

using Stuff

export f, g, h

include("./f.jl")
include("./g.jl") 
include("./h.jl")

end

where f.jl and others are just plain code files (without modules).

3 Likes