Is there a way overload a function, `fn`, in a `Module Module1` so that it can only be called using `Module1.fn`?

I am defining size in my module JDF, but I only want it to ever be called using JDF.size. Can I do that?

module JDF

using Base:size

JDF.size(df, val) = JDF.size(df, Val(val))

JDF.size(df, ::Val{1}) = 1
JDF.size(df, ::Val{2}) = 2
end

Now

@which size("abc", 1)

shows the location in my JDF, even though I didn’t export it.

Is there a way to do it so that JDF.size needs to be called and size ignores the function defined in the module JDF?

Your code as written is invalid for multiple reasons:

  1. first, you want using Base: size

  2. second, you can’t redefine size without importing it, so that part will error too.

So I am curious how you got this even to run.

Do you need something like

baremodule JDF
using Base: Base, Val
size(df, val) = size(df, Val(val))
size(df, ::Val{1}) = 1
size(df, ::Val{2}) = 2
end

?

2 Likes

My actual code was a lot longer, so I try to get the essence by writing a MWE. Fixed.

You didn’t fix it — please read item 2; code above still errors.

Truly fixed now. I just ran it. I think I encountered the error and had done what I have been doing there. At some point I had import Base: size. Maybe that’s why it didn’t work.