Extend julia module

Hi.
I try to understand modules in julia.
And cant figure out how to extend julia module.

Suppose i have a module:

module Test 
   t :: Float64 = 0
end

how to add new function or variable to the module from another file (or even file with declared module)?

New module declaration will override the previous.

Thanks

Let’s say you have a module Foo in file Foo.jl

module Foo
foo() = "hello!" 
end

And you’d like to add more to the module. The most common way is to include another file, for example bar.jl

module Foo
include("bar.jl")
foo() = "hello!" 
end

Then you can place code in bar.jl

bar(name) = "hello $name" 

Thanks for response!

So i should modify module directly to extend?
No option like c++ namespaces. In REPL i will owerwrite module each time when i add something?

From what I know yes, you have to enclose everything between module MODULE_NAME and its corresponding end.

It’s not clear what your use case is but one possible answer is that you can eval new things into an existing module.

julia> module Test
       f() = 1
       end
Main.Test

julia> @eval Test begin
       g() = 2
       end
g (generic function with 1 method)

julia> Test.f()
1

julia> Test.g()
2

4 Likes

Another way to extend a module from outside is multiple dispatch, that is, adding new methods for functions that are defined inside that module

4 Likes

You cannot introduce new values and functions to a module’s namespace externally without an @eval solution like @GunnarFarneback proposed, which sidesteps the issue because it evaluates the code within the module Test.

There is a standard way to extend a module in a somewhat restricted way: add methods to an existing function (what @gdalle mentioned).

julia> module A
       greeting() = "hello"
       end
Main.A

julia> A.greeting()
"hello"

julia> A.greeting(name) = "hello $name" 

julia> A.greeting("Sergey")
"hello Sergey"
3 Likes

Thank for examples!