Module with one function of same name as the module?

pkg
module
#1

I have a module that contains precisely one exported function. Is it possible to give the module and the function the same name and use them with the syntax below?

e.g. for the module:

module myfunc

export myfunc

function myfunc(args)
    return mystuff
end

end

I want to import and use with something like:

using myfunc
mystuff = myfunc(args)

Is there a way to do this (or similar), or do I just need to come up with a different name for the module than the function?

0 Likes

#2

It is a (quite strong) convention in Julia to write modules in CamelCase, so it would be called MyFunc. Is there a reason it is getting wrapped in a module?

2 Likes

#3

Thanks! The module wrapping is mostly because my impression is that this is the way to deploy the code for other people to use? There are also some non-exported functions within the module that are used by the main function.

0 Likes

#4

In that case a module seems like a great idea, but I’m afraid that you can’t have your function and module share the same name.

0 Likes

#5
julia> module a
       _a() = println("Hello there!")
       function Base.getproperty(m::Module, x::Symbol)
           if m === a && x === :a
               return getfield(m, :_a)
           else
               return getfield(m, x)
           end
       end
       end
Main.a

julia> a.a()
Hello there!
0 Likes

#6

Definitively don’t actually do this, though, since it modifies the way module lookup happens for every module, not just yours.

3 Likes

#7

Agreed on definitely not using, although it should technically be safe due to the checks. Constant propagation will likely also make it free.

0 Likes

#8

Agreed. Like all type piracy, it’s probably fine as long as only one person in the entire universe does it :wink:

1 Like

#9

Thank you!

The original desire to use only one name came because it’s a port of something from a different language, and I wanted to keep the API as consistent as possible. But in the end I’ve just come up with an acceptable alternative name for the container module.

1 Like