What is the best way to override a function in different modules?

Hi,

What is the best practice to make sure to avoid the following type of warnings?

WARNING: both ABM_Sim and Production export "produce!"; uses of it in module Main must be qualified

I have 2 modules where I defined the produce!() function, both with different parameters. I use the first module in the second one.

What is best practice to avoid name conflicts and to make maximum use of the multiple dispatch functionality of Julia?

Thanks in advance,
Stef

Unless you import the function name produce! from the other module, the two produce! are two different functions that just happen to have the same name. If instead you import the function, you’re adding a new method, with a different signature, to the same function

4 Likes

More explicitly, if ABM_Sim defines a function produce! and you want to add a new method in the module Production, you have two options. Either explicitly import it:

import ABC_Sim: produce!    # explicitly import produce! to add new methods
function produce!(....)   # new method
    ...
end

or explicitly qualify the name when you define the new method:

function ABC_Sim.produce!(....)   # new method for ABC_Sim's function
    ...
end

Mostly I would suggest use the latter style.

3 Likes

PS. Where is this clearly explained in the manual? It doesn’t seem to be mentioned in the Functions chapter or the Methods chapter, and the Modules chapter only devotes two sentences to the subject.

Update: ah, in the latest version, @Tamas_Papp added some documentation in https://github.com/JuliaLang/julia/pull/38271

I do this in my package GuillotineModels.jl: I have the package module defining some function like solution_value, that should have methods implemented for different combinations of problems and instances, and in the inner modules (of the same package, inside the GuillotineModels module) I import the solution_value and extend it. I do so because I want solution_value to be available by people using my main module, but at the same time, its methods are better implemented in inner modules that implement the instances for which the methods are specialized, and already have them in scope.

2 Likes