Sub module accessing a global method

This is a lot of code to try to understand all at once, but I think I can make a guess as to what is going on. I suspect you are doing something like this:

julia> module Outer
         export f
         f(::Int) = 1

         module Inner
           using ..Outer
           f(::Float64) = 2 # BAD: this is *not* a new method for Outer.f, but instead a brand-new function with the same name.
           
           f(1) # this fails because Inner.f is a function with just one method: f(::Float64).
         end
       end
WARNING: replacing module Outer.
ERROR: MethodError: no method matching f(::Int64)
Closest candidates are:
  f(::Float64) at REPL[7]:7

Instead, you need to explicitly extend the method from the other module, just as you do with all other methods in Julia:

julia> module Outer
         export f
         f(::Int) = 1

         module Inner
           using ..Outer
           Outer.f(::Float64) = 2 # GOOD: we are explicitly adding a new method to Outer.f, not making a new function with the same name
           @show f(1) f(1.0) # this works!
         end
       end
WARNING: replacing module Outer.
f(1) = 1
f(1.0) = 2

Alternatively, instead of:

using ..Outer
Outer.f(...) = ...

you could also have done:

import ..Outer: f
f(...) = ...

which has the same effect.

The presence of nested modules doesn’t affect the behavior of this at all: you will experience the same issue regardless of whether Inner happens to live inside Outer or not.

5 Likes