While playing around with Dict
s, I found that I was not able to use the do-block syntax, e.g.
get(a, key) do
@warn "Key not found. Falling back to default"
default
end
when a
is of type Base.ImmutableDict
instead of Dict
. Is there a reason it isn’t implemented, and is there a workaround I can use instead? (I guess I could make a custom version of the function by looking at dict.jl on GitHub though I’m not sure that’s the best idea)
Seems like an oversight (a missing fallback method for AbstractDict
), since the documentation lists get(f::Function, collection, key)
as a generic method for any collection. Maybe file an issue?
As a workaround, you could define something like
struct _KeyNotFound; end
function myget(default::Base.Callable, collection, key)
result = get(collection, key, _KeyNotFound())
return result isa _KeyNotFound ? default() : result
end
2 Likes
Thank you, that is a more elegant workaround than what I had come up with! I will file that as an issue as well.