Wednesday, August 24, 2022

[FIXED] Why is a function from a Julia submodule being shadowed?

Issue

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.


Solution

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


Answered By - Andrej Oskin
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.