Trouble importing a module that depends on another globally imported module

Perhaps you’re defining the module multiple times by using include? This can be very confusing because it redefines a new module with the same name, and is rarely what you want. Instead you should add your module to the load path and it will be found automatically by using, or at least have a single file which includes both modules exactly once.

Consider the following sad and confusing story-in-code:

julia> module A
           struct B end
           foo(b::B) = "something"
       end
Main.A

julia> b = A.B()
Main.A.B()

julia> A.foo(b)
"something"

julia> OldA = A
Main.A

julia> module A
           struct B end
           foo(b::B) = "something"
       end
WARNING: replacing module A.
Main.A

julia> A.foo(b)
ERROR: MethodError: no method matching foo(::Main.A.B)
Closest candidates are:
  foo(::Main.A.B) at REPL[11]:3
Stacktrace:
 [1] top-level scope at none:0

julia> b isa A.B
false

julia> b isa OldA.B
true

Note the “WARNING: replacing module A”. If you ever see this kind of thing, it means you’ve redefined a module with the same name as an existing module. Any variable b which you had hanging around from the old module is still available, but it has the type OldA.B (printed as A.B) rather than A.B (also printed as A.B!). This might be the problem you’re having if you’re calling include multiple times on a file with the module code inside.

4 Likes