How to use `getproperty`/`setproperty!`?

The recommended way to implement getproperty(value, name::Symbol) is by making as many branches as required to check what name is?
This seems inefficient. Or is the compiler able to eliminate the branching when it sees a.b (hence knows the actual symbol used)?

1 Like

Yes, it can generally eliminate the branches.

1 Like

Yes, the compiler normally inlines and eliminates the branches when you call getproperty via a.b. (This is a constant-propagation optimization that was added in Julia 0.7.)


Two more questions.

  1. Is there a macro to make adding properties easy? For example, something that automatically handles propertynames?
  2. If someone writes a.b = v on a property that should not be set, what is the error that setproperty! should throw?

I don’t think there is any package for this yet.

Various packages have probably rolled their own utilities for this. e.g. in ZMQ.jl I wrote a little utility function to automatically generate the long sequence of if … elseif … checks from a list of property symbols and corresponding functions to dispatch to for each property. See e.g. how the long list of ZMQ.Socket properties is implemented.

Something like error(typeof(value), " has no writable field ", name) seems common; as far as I can tell there is no special exception type for this.


There is no issue with getproperty not being type stable?

No, because of the constant propagation mentioned above: all of the branches except for the symbol you want are stripped out before inference.