Programmatically generated function, how to define doc?

Viewed 58

I want to define some functions as described in the official doc but with some documentation.

Minimal reproducible example :

julia> cases = ( :A => 1, :B => 2 )
(:A => 1, :B => 2)

julia> for (name,value) in cases
           func_name = Symbol("foo_"*string(name))
           eval(quote
                    $func_name() = $value
                end)
       end

julia> foo_A()
1

julia> foo_B()
2

My problem is that I want to also define some associated doc :

help?> foo_A
search: foo_A foo_B unsafe_pointer_to_objref

  No documentation found.

  foo_A is a Function.

  # 1 method for generic function "foo_A":
  [1] foo_A() in Main at REPL[2]:4

I can do :

for (name,value) in cases
    func_name = Symbol("foo_"*string(name))
    eval(quote
             " The function doc is here "
             $func_name() = $value
         end)
end

in that case :

help?> foo_A()
  The function doc is here

But what I really need is some kind of substitution :

julia> for (name,value) in cases
           func_name = Symbol("foo_"*string(name))
           eval(quote
                    " The function $name returns $value"
                    $func_name() = $value
                end)
       end
ERROR: UndefVarError: name not defined

Is it possible ?

1 Answers

Use the @doc macro:

for (name,value) in cases
    func_name = Symbol("foo_"*string(name))
    docstr = " The function $name returns $value"
    eval(quote
        @doc $docstr $func_name() = $value
    end)
end

Now yo can do as expected:

julia> foo_A(), foo_B()
(1, 2)

help?> foo_A
search: foo_A foo_B unsafe_pointer_to_objref

  The function A returns 1

help?> foo_B
search: foo_B unsafe_pointer_to_objref foo_A

  The function B returns 2

Related