Is it possible to use @example in docstrings?

I would like to use the @example in my docstrings so that it is displayed in the api section of the documentation. The code is displayed in the documentation, but not the output. Is there a way to make it work?

I think you may use the following

julia> """
           A

       Return A

       # Examples
       ```julia
       x = A()
       ```
       """
       struct A end
A

help?> A
search: A Any any all abs ARGS ans axes atan asin asec any! all! acsc acot acos abs2 Array atanh atand asinh asind asech asecd ascii angle acsch acscd acoth acotd acosh acosd atexit

  A

  Return A

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  x = A()

But I think the actual answer to your question is no, because doing so would amount to running code to display docstrings. This can be done while building the documentation with Documenter.jl, but as far as I know it is not possible in the language itself

1 Like

Thank you for your replies. Just to clarify, I do not want to run the examples as code in the REPL. Instead, I would like it to display in the documentation that Documenter.jl produces via @autodocs. Currently, it only displays the code, but not the output. However, if I use @example directly in an .md file, it works.

1 Like

As a concrete example, the documentation for ACTR (top of the page) generated by @autodocs does not run the example.

OK I misunderstood your question but I think my answer might still be valid. If I understand correctly, @autodocs copies the docstring (as does the REPL help mode) while @example runs it during docs build. It could be a nice feature request for Documenter though.

1 Like

Thanks again for your reply. I will submit a feature request. I don’t know if this is difficult to achieve from a technical perspective, but it could be useful, and from the perspective of a user, I expected it to work.

1 Like

I don’t think we want this behavior in Documenter (it has been discussed before). Documenter’s goal is to reflect the docstrings as they appear in other contexts too (REPL, IDE docs browsers etc). Dynamic stuff in docstrings is usually handled by things like DocStringExtension.

The options here would be either to (a) put the examples near the docstring in the manual, and refer to them in the docstring, or (b) for text-only outputs, you can use doctests in the docstrings (and doctests make sure they’re always up to date; and can also update the snippets for you).

4 Likes