Private Properties in Julia 0.7

Julia 0.7 supports method propertynames(x, private=false)
The latest documentation for that method reads

‘‘propertynames(x) may return only “public” property names that are part of the documented interface of x. If you want it to also return “private” fieldnames intended for internal use, pass true for the optional second argument. REPL tab completion on x. shows only the private=false properties.’’

Does Julia 0.7 let you define a property/field as readonly when you define a (mutable) struct,
or is the overloaded method propertyname responsible for enforcing private=true?

How does the REPL know when a property is private?

Also, how are methods getproperty, and setproperty expected to deal with private properties?

Thanks.

3 Likes

This has no influence on running code, it is purely for documentation and things like tab completion.

2 Likes

OK, I take it that the property related methods will have to enforce private=true if desired.
But how does “tab completion” (i.e. the REPL) know that a property is supposed to be private?

It only looks at the propertynames(x, private=false). It’s up to x to return the appropriate thing. Right now, the default definition for a struct will return all its fields.

1 Like

Can create private properties by defining:

struct MyType
    a
    b
end

function getpublicproperties(x::MyType, field::Symbol)
    if field == :a
        getfield(x, :a)
    else
        error("Not a public property")
    end
end

function getallproperties(x::MyType, field::Symbol)
    getfield(x, field)
end

function Base.getproperty(x::MyType, field::Symbol; public = true)
    if public
        getpublicproperties(x, field)
    else
        getallproperties(x, field)
    end
end

then you get:

julia> x = MyType(1, 2)
MyType(1, 2)

julia> x.a
1

julia> x.b
ERROR: Not a public property
Stacktrace:
 [1] error(::String) at ./error.jl:33
 [2] getpublicproperties at ./REPL[2]:5 [inlined]
 [3] #getproperty#4 at ./REPL[8]:3 [inlined]
 [4] getproperty(::MyType, ::Symbol) at ./REPL[8]:2

julia> getproperty(x, :b, public = false)
2

I am sure you can do some macro-magic to define these things nicely.

9 Likes