Hi everyone,
Let’s say I have a package that provides some functions. Of these functions only a few depend on some global data downloaded from the internet. The package should be able to download the data automatically but should not force this on the user (e.g. calling it in __init__
) because they might already have the data elsewhere. Also the rest of the package should work even if the data is not available.
The question is what would the type of this “optional data” be?
module SomeModule
# What am I?
const data = ?
# I don't need the data
f(x) = 1.0x
# I don't need the data
g(x) = 2.0x
# I need the data and will error if it's not here
h(x) = data*x
end
I have experimented with several solutions and would like to know which one you would prefer.
-
Nullable
Works in principle but gives a constant redefinition warning when the data is made available.
const data = Nullable{TypeOfData}() function download() global data file = download(...) # Will give a constant redefinition warning data = Nullable(TypeOfData(file)) end function h(x) if isnull(data) error() end get(data)*x end
-
Wrap
Nullable
in a mutable typetype OptionalData{T} data::Nullable{T} end OptionalData{T}(::Type{T}) = OptionalData(Nullable{T}()) function push!{T}(opt::OptionalData{T}, data::T) opt.data = Nullable(data) opt end get(opt::OptionalData) = get(opt.data) isnull(opt::OptionalData) = isnull(opt.data) const data = OptionalData(TypeOfData) function download() file = download(...) push!(data, TypeOfData(file)) end function h(x) if isnull(data) error() end get(data)*x end
-
Just use a
Ref
const data = Ref{TypeOfData}() function download() file = download(...) data[] = TypeOfData(file) end function h(x) if !isassigned(data) error() end data[]*x end