Type stable specializations of `getproperty` without code duplication?

Reviving this topic instead of opening a new one, hope that is OK.

I found that with something like the following tiny utility function, one can automate the fallback to getfield in Julia 1.10:

Base.@constprop :aggressive function getfield_or_dispatch(value::T, key::Symbol) where T
    @assert isstructtype(T)
    if key āˆˆ fieldnames(T)
        getfield(value, key)
    else
        _getproperty(value, Val(key))
    end
end

Eg

@inline function Base.getproperty(foo::Foo, key::Symbol)
    getfield_or_dispatch(foo, key)
end

_getproperty(foo::Foo, ::Val{:calculated}) = 1

is then inferred in the contexts I have tested.

Now I am wondering whether to package this up in a tiny library, and if yes, what the API should be. A macro could take care of the getproperty indirection. And I defining methods for getproperty(foo, ::Val{thingy}) is not technically type piracy but a bit smelly.

3 Likes