How to document type properties defined with `getproperty`?

Consider the structs Foo and Bar:

"""
Doc for type `Foo`.
"""
struct Foo
  """
  Doc for field Foo.x
  """
  x::Int
  Foo() = new(2)
end

"""
Doc for type `Bar`.
"""
struct Bar end

Base.propertynames(::Bar) = (:x,)

function Base.getproperty(a::Bar,s::Symbol)
  if s == :x
    2
  else
    error("type Bar has no field $s")
  end
end

function Base.show(io::IO,::Bar)
  print(io,"Bar(2)")
end
 

They have an (almost) identical API

julia> foo = Foo()
Foo(2)

julia> bar = Bar()
Bar(2)

julia> foo.x
2

julia> bar.x
2

Except for documentation

help?> Foo.x
  Doc for field Foo.x

help?> Bar.x
  Bar has no fields.

Is there any way of documenting the property Bar.x ?

Thanks for the help!

This is currently an open question, and there is no solution for it that would replicate the convenience of the field docstring. Cf

https://github.com/JuliaLang/julia/issues/27119

I would suggest documenting valid properties in the docstring of Foo, or the usual function that users call to make Foo.

1 Like

Thanks for answering!

Another solution I can think of is to create a getter getx(a::Bar) = a.x and document this getter and inform the users of the package that properties are documented in the corresponding getter.

Do you see any problem with this?

If there is an explicit accessor function, it is of course good practice to document that.

But one advantage of property accessors is that you don’t have to bother with defining a function for this. How to document that is somewhat of an open question while practice evolves, but at least discoverability is fine thanks to propertynames.

2 Likes