Hi all,

I'm thinking about how to translate a Python interface that makes extensive
use of __getattr__ and __setattr__ overloading to allow chaining a series
of option values like this example:
mysolver.linear_system.parameters.solver_type = "GMRES"

Each time a . is encountered, the appropriate __getattr__ is called, which
in turn calls a C++ function to get the correct value, which may not be
stored as a true data field member anywhere. In the end, the assignment
triggers a call to __setattr__ and may call additional functions to notify
functions of the change. I see 3 ways of tackling this in Julia:

1. Just use methods to get/set each field, so something like:
setproperty(getproperty(getproperty(mysolver, "linear_system"),
"parameters"), "solver_type", "GMRES")
As is obvious from the example, this is a bit cumbersome and hard to read
with a long chain of gets.

2. Use the [] operator, which can be overloaded, as far as I understand.
The question there is if we use strings or symbols as keys, to get either:
mysolver["linear_system"]["parameters"]["solver_type"] = "GMRES"
or:
mysolver[:linear_system][:parameters][:solver_type] = "GMRES"
Either solution is still not as readable or easy to type as the Python
original

3. Finally use a macro, such as enabled by the DotOverload.jl package (
https://github.com/sneusse/DotOverload.jl):
@dotted mysolver.linear_system.parameters.solver_type = "GMRES"

I realise this touches on the discussion on . overloading at
https://github.com/JuliaLang/julia/issues/1974 but that seems to have dried
out a bit, and I understand that touching an operation that is expected to
have (almost?) no inherent cost such as field access may be dangerous. The
macro solution in 3 seems like the most elegant method, but I worry about
code readability, since the purpose of the @dotted will not be immediately
clear to people unfamiliar with the DotOverload package. Could a macro like
this be provided in Base, with proper documentation (near the descriptions
of types and their fields, for example), so option 3 can be used without
concerns over code readability/understandability?

Cheers,

Bart

Reply via email to