How can you use functions from outside the module inside the module

Basically, I want a module that can use functions that are not in its scope. I need this because my work will only provide an environment in which the user can enter their own code. Something like that

Simulation.jl

abstract AbstractType function startSimulation(unknown::AbstractType) doStuff(unknown) end 

Mymodule.jl

 module MyModule include("Simulation.jl") export AbstractType, startSimulation end 

SomeImplementation.jl

 type ConcreteType <: AbstractType variable::Int64 end doStuff(me::ConcreteType) me.variable end 

and finally Main.jl

 # push!(LOAD_PATH, pwd()) # for local usage using MyModule include("SomeImplementation.jl") startSimulation(ConcreteType(5)) 

Where Simulation.jl and MyModule.jl are written by me, and SomeImplementation.jl and Main.jl are written by the user.

Now the above example does not work, because the modules have their own namespace, and even SomeImplementation.jl is imported into main on line 3, the interpreter will not see it on line 4 of the Simulation.jl model.

I can’t import anything into MyModule.jl because I don’t know how the user will name his material or what additional libraries he might even need.

Is there any way to do this using modules? Otherwise, I simply will not use modules.

+5
source share
1 answer

The answer here is to create stubs for all the functions that you want to call in MyModule , as a necessary interface for AbstractType user subtypes. That is, within MyModule you will have:

 abstract AbstractType doStuff(::AbstractType) = error("custom AbstractType objects must define a `doStuff` method) function startSimulation(unknown::AbstractType) doStuff(unknown) end 

Then, specific implementations just need to specifically add their doStuff method to the function in MyModule, importing it or assigning it a value:

 MyModule.doStuff(me::ConcreteType) me.variable end 
+10
source

Source: https://habr.com/ru/post/1266938/


All Articles