Why is it Convention to Repeat Function Signatures in Docstrings

Yes! Why not have the compiler insert the method signature automatically? Shouldn’t this be extremely easy to implement, even at a syntactic level? When you see code like this:

"Some documentation"
function func(x::Whatever{T}, default::Real=0.5; keyword::Integer=5)::SomeType where T<:Real
   # whatever
end

…prepend the current function’s signature to the docstring, so the transformed code will become (internally in the compiler, not literally in the source code):

"""`func(x::Whatever{T}, default::Real=0.5; keyword::Integer=5)::SomeType where T<:Real`

Some documentation
"""
function func(x::Whatever{T}, default::Real=0.5; keyword::Integer=5)::SomeType where T<:Real
   # whatever
end

The compiler likely knows what “function signature” means at this point, so other kind of function definitions like func(x) = 5 or function func(::Vector{T}) where T<:Real should work too.

Julia can output method signatures when there’s no documentation, so these could be used for inserting into docstrings. Unfortunately, currently Julia doesn’t keep default values, types of keyword arguments and return types when printing methods:

julia> function func(a::Real, b::Integer=5, c='f'; kwd::Vector{T}, kwd2::Real=3.141)::Float64 where T<:Real
        5.6789
       end;

help?> func
search: func trunc sinc function run

  No documentation found for private symbol.

  func is a Function.

  # 3 methods for generic function "func" from Main:
   [1] func(a::Real, b::Integer, c; kwd, kwd2)
       @ REPL[1]:1
   [2] func(a::Real, b::Integer; ...)
       @ REPL[1]:1
   [3] func(a::Real; ...)
       @ REPL[1]:1

None of the signatures show that b::Integer, c and kwd2 have default values. kwd and kwd2 look the same in signatures, but 1) they have different types and 2) only kwd2 has a default value, so the printed signature doesn’t tell the full story. Why not?

Does the compiler know that all 3 methods come from the same piece of code? If so, why not put each call signature into each method’s docstring?

When I add a docstring, I get:

julia> begin
        "Docstring"
        function func2(a::Real, b::Integer=5, c='f'; kwd::Vector{T}, kwd3::Real=3.141)::Float64 where T<:Real
         1.2345
        end
       end;

help?> func2
search: func2 func function

  Docstring

…which is plain confusing, because it refuses to tell me how to call the function, even though it can do that, as we saw above. An uninformative docstring remains uninformative.

Whenever a method is documented, the appropriate signature could be automatically included in the documentation. This will also make it impossible to forget to change the signature in the docs after changing the signature in code.

Why not implement this? Does it become too complicated? Is nobody interested in such a feature? Seems like a 100% win-win to me.

1 Like