How can I programmatically access DocStrings?

I am writing a macro that takes the name of a function and declares a couple of other versions of the function. I want to give these variations the same line of the document as the original method, possibly a few changes.

For this, I need to get a docstring for the original method.

So, I am looking for a function:

get_docstring(functionname::Symbol, argtypes)::String

So that I can:

julia> s=get_docstring(:values,(Associative,)), and then the svalue will be set:

s="""
    values(a::Associative)
Return an iterator over all values in a collection.
`collect(values(d))` returns an array of values.
```jldoctest
julia> a = Dict('a'=>2, 'b'=>3)
Dict{Char,Int64} with 2 entries:
  'b' => 3
  'a' => 2
julia> collect(values(a))
2-element Array{Int64,1}:
 3
 2
```
"""
+4
source share
1 answer

You can use a macro @doc, but instead of a string, it returns a markdown object:

julia> @doc "foo int" ->
       foo(x::Int) = x
foo

julia> @doc "foo float" ->
       foo(x::Float64) = x
foo

julia> @doc "foo sym" ->
       foo(x::Symbol) = x
foo

julia> @doc "foo x, y" ->
       function foo(x, y) x, y end
foo

julia> @doc foo
  foo int

  foo float

  foo sym

  foo x, y

julia> typeof(ans)
Base.Markdown.MD

julia> @doc foo(::Int)
  foo int

julia> @doc foo(::Float64)
  foo float

julia> @doc foo(::Symbol)
  foo sym

julia> md = @doc foo(::Any, ::Any)
  foo x, y

julia> md.content
1-element Array{Any,1}:
 foo x, y

julia> md.content[1]
  foo x, y

julia> md.content[1].content
1-element Array{Any,1}:
 Base.Markdown.Paragraph(Any["foo x, y"])

julia> md.meta
Dict{Any,Any} with 3 entries:
  :typesig => Tuple{Any,Any}
  :results => Base.Docs.DocStr[Base.Docs.DocStr(svec("foo x, y"),foo x, y…
  :binding => foo

julia>
+3
source

Source: https://habr.com/ru/post/1654320/


All Articles