How to access function documentation in a script

Is there a way to access the documentation string associated with a function that is part of a module?

Consider this example:

module Test

export f

"""
    f(x)

Return `x` squared.
"""
function f(x)
    return x^2
end

end  # module Test

using .Test

function getDocString(g)  # I would like g::Union{Symbol, String}
    return @doc g  # unsure what to put here
end

println(getDocString(f))
# note that `println(@doc f)` does work, but it's not what I want.

Running this as a script gives the error:

No documentation found.

Binding `g` does not exist.

Is there a way to write a function that takes a function argument (represented as a symbol/string) and returns its docstring? I’m probably not understanding how modules relate docstrings to their corresponding functions. I know that I can use @doc f to access function documentation, but I’d like to use symbols/strings to get this result as well. @doc is great to use in the REPL. However, I’m looking for a more script-oriented approach. :smile:

As a clarifying example, say I generated the symbol :f and I know there’s a function defined in Test with that name. How would I get f’s docstring with only a symbol?

From the macro expansion it looks like you just need Docs.doc(g).

Thanks for the quick response, @Vasily_Pisarev!

Are you suggesting something like this?

function getDocString(g::Symbol)
    return Docs.doc(g)
end

println(getDocString(g))

If so, this still gives an error. I may be misunderstanding your response. Also, I’d like to get the docstring from a symbol (:g), not g. I hope this clarifies. It’s certainly a weird question. :wink:

function getDocString(g::Symbol)
    return Docs.doc(Docs.Binding(Main, g))
end

?
(I’m just copy-pasting @macroexpand @doc g output :wink:)

3 Likes

Unfortunately, this doesn’t work for my example above. See the output below:

#...
using .Test

function getDocString(g::Symbol)
    # return Docs.doc(Docs.Binding(Test, g))  # Also doesn't work
    return Docs.doc(Docs.Binding(Main, g))
end

println(getDocString(:g))

Using this in the example script above, I get the error:

No documentation found.

Binding `g` does not exist.

But is there a binding for :g in Test? From the snippet in OP, the only binding in Test is :f.

:man_facepalming:

Thanks a lot! Maybe I need to eat something. :laughing: