Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a function from a Julia submodule being shadowed?

Consider the following code:

module Foo
export g, h

  module Bar
  export f

  f(::Int) = 2

  end

using .Bar

f(::String) = "abc"

g() = f("a")
h() = f(12)

end

When I run this, if I try calling g() I get "abc" as expected. If I call h() I get an error message. Somehow, the definition of f(::Int) is being shadowed. Is that supposed to happen? How to fix this?

If I omit the definition of f(::String) then h() works.

like image 228
Fernando Avatar asked Sep 17 '25 07:09

Fernando


1 Answers

Yes, this is correct behaviour. In order to extend method it should be imported (https://docs.julialang.org/en/v1/manual/modules/#using-and-import-with-specific-identifiers,-and-adding-methods)

So, correct example should look like this:

module Foo
export g, h

  module Bar
  export f

  f(::Int) = 2

  end

using .Bar
import .Bar: f

f(::String) = "abc"

g() = f("a")
h() = f(12)

end

I've added import .Bar: f because Bar can export other names, which you do not want to extend. So it is fine to mix these two together. With this addition, everything is working as intended

julia> using .Foo

julia> g()
"abc"

julia> h()
2
like image 183
Andrej Oskin Avatar answered Sep 22 '25 02:09

Andrej Oskin