Jupyter with Julia results in unexpected type error: no method matching

Viewed 45

I get an unexpected type error when running the following Julia code in Jupyter, where a seemingly straightforward import goes wrong:

include("./imp.jl")
include("./imp2.jl")
n = Main.Imp.Network([1,2])
Imp2.p2(n)

This results in the following error:

MethodError: no method matching p(::Main.Imp.Network)
Closest candidates are:
  p(::Main.Imp2.Imp.Network) at /Users/cg/Dropbox/code/Julia/learning/imp.jl:11

The code is the below. How does this happen?

Imp.jl:

module Imp

export Network, p

mutable struct Network
  a::Array{Any,1}
end

function p(network::Network)
  network
end

end

Imp2.jl:

module Imp2
include("./imp.jl")

function p2(network)
  Imp.p(network)
end

end

More error below:

Stacktrace:
 [1] p2(network::Main.Imp.Network)
   @ Main.Imp2 ~/Dropbox/code/Julia/learning/imp2.jl:5
 [2] top-level scope
   @ In[3]:4
 [3] eval
   @ ./boot.jl:360 [inlined]
 [4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1116
1 Answers

You can either do:

module Imp2
using Main.Imp
function p2(network)
  Imp.p(network)
end
end

OR (without sourcing imp.jl outside of module defintion)

module Imp2
include("./imp.jl")
using .Imp
function p2(network)
  Imp.p(network)
end
end

In the second case your Julia code could look like:

julia> using Main.Imp2

julia> n = Imp2.Imp.Network([1,2])
Main.Imp2.Imp.Network(Any[1, 2])

julia> Imp2.p2(n)
Main.Imp2.Imp.Network(Any[1, 2])

Addtionally if you add export Imp to the Imp2 module, you could write Imp.Network([1,2]) instead of Imp2.Imp.Network([1,2]).

Related