API to retrieve the docstring of a function

I would like to programmatically get the docstring associated to a function – is that possible?

On a related note, how can we apply reflection and introspection techniques to functions? In Julia functions are first-class, but they don’t seem to behave like standard objects (as least the way one might expect by comparison with other languages). What kind of beast is this? :japanese_ogre:

julia> g = (x) -> 2x
(::#23) (generic function with 1 method)

julia> typeof(g)
##23#24

julia> isa(g, Function)
true

julia> f = Function()
ERROR: MethodError: no constructors have been defined for Function

julia> fieldnames(typeof(g))
0-element Array{Symbol,1}

julia> methods(g)
# 1 method for generic function "(::#23)":
(::##23#24)(x) in Main at REPL[8]:1

julia> methods(Function)
# 1 method for generic function "(::Type)":
(::Type{T})(arg) where T in Base at sysimg.jl:77
1 Like
Base.doc(Base.Docs.Binding(Base.Docs.current_module(),:rand))

You can find this using macroexpand( :(@doc rand) ).

Otherwise you often want to look at methods instead of functions:

julia> m = collect(methods(rand))[1]
rand(rd::RandomDevice, ::Type{T}) where T<:Union{Bool, Int128, Int16, Int32, Int
64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} in Base.Random at random.jl:40


julia> fieldnames(m)
19-element Array{Symbol,1}:
 :name
 :module
 :file
 :line
 :sig
 :min_world
 :ambig
 :specializations
 :sparam_syms
 :source
 :unspecialized
 :generator
 :roots
 :invokes
 :nargs
 :called
 :isva
 :isstaged
 :pure
3 Likes

Excellent, thank you!