Definition of unary operator inside a module, removes the `Base` definition

i have a module in which a dispatch on + is defined

module DriftDiff
 function (+)(l::Layer, r::Layer)
  ...
 end

 function b()
  1.0+10.0
 end
end

If i call now the function b()

julia> DriftDiff.b()
ERROR: MethodError: no method matching +(::Float64, ::Float64)
You may have intended to import Base.+

How can i make DriftDiff.b() work again?

What you did is to define a new function named +, which doesn’t remove the Base definition but shadows it so that it is not visible as + within your module. This is a useful default because it prevents unexpected behaviors if you accidentally give a function the same name as some obscure Base function. You can still refer to the Base definition via Base.:+.

However, as the error message suggests, what you probably meant to do is to extend the + function in Base with a new method for your Layer type, rather than defining an entirely new function called +. One way to do this, as the error message suggests, is to explicitly import the + function before defining your method, via import Base: +. More commonly, you can specify that you are extending Base.+ when you define your method:

function Base.:+(l::Layer, r::Layer)
  ...
end

(The special “quoted” syntax Base.:+ is only required when extending operators, in order to disambiguate the syntax from a binary operation Base .+ (...). You wouldn’t need it for adding methods to e.g. Base.div)

3 Likes

Excellent thanks

One way to do this, as the error message suggests, is to explicitly import the + function before defining your method, via import Base: +

This was my problem, because the message says import Base.+ and this I’ve tried without luck, now I know that it has to be Import Base:+.

Thanks for teaching me !!

import Base.+ should work (if you do it in the module before your function definition). However, if you want to qualify the function name itself, you have to quote it with : as Base.:+.

It seems a little inconsistent, so I filed a PR to fix both the error message and to allow quoting in import statements:

4 Likes