dantheman
dantheman

Reputation: 131

Using a Julia module to store values set by other modules

I'm trying to create a Factory module for certain types and the types modules themselves can register themselves and their parameters for being created.

I think this is it simplified:

module Factory
    export register

    const factories = Dict()

    function register(t::Type{T}, params) where T <: AbstractModel)
        factories[t] = params
    end
end

and then in a model (let's say 'Persons')

module Persons
    import Factory: register

    struct Person
        name::String
    end

    @show Factory.factories  # empty
    register(Person, Dict(:name="my name"))
    @show Factory.factories  # not empty
end

It's more complicated than this but I think this covers my basic problem which is that when I load the Persons module it appears to have added something to the Factory module but when I check Factory.factories from the REPL it is still empty.

Upvotes: 0

Views: 115

Answers (1)

Stepan Zakharov
Stepan Zakharov

Reputation: 747

import Factory: register

brings only register in scope (see this). Perhaps, REPL session messed things up too.

Anyway, this works for me

module Factory
    export register

    const factories = Dict()

    function register(t::Type, params)
        factories[t] = params
    end
end # module

module Persons
    using ..Factory  # brings both Factory and register in scope

    struct Person
        name::String
    end

    @show Factory.factories
    register(Person, Dict(:name => "my name"))
    @show Factory.factories
end  # module
% j -i stack.jl
Factory.factories = Dict{Any, Any}()
Factory.factories = Dict{Any, Any}(Main.Persons.Person => Dict(:name => "my name"))
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.6.2 (2021-07-14)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia> Factory.factories
Dict{Any, Any} with 1 entry:
  Person => Dict(:name=>"my name")

Upvotes: 1

Related Questions