function define_ops(x)
for sym in (:pos, :pes)
@eval $(sym)(y) = y + $x
end
end
define_ops(2)
pos(3) #5
Works perfectly
But if I try to do it in a module (I believe eval works in module scope?), it doesn’t:
module FooMod
function define_ops(x)
for sym in (:pos, :pes)
@eval $(sym)(y) = y + $x
end
end
export define_ops
export pos, pes
end
using FooMod
define_ops(2)
pos(3) # 'pos not defined' error
clearly something about scoping I don’t understand. What idiom would I use to make the below version work?
I think you might need to eval in current_module():
eval(current_module(), ...)
(which might later be superseded by @__MODULE__)
help?> current_module
search: current_module
current_module() -> Module
Get the dynamically current Module, which is the Module code is currently being read from. In general, this is not the same as the module containing the call to this function.
No don’t eval in current_module(). It is also NOT equivalent to @__MODULE__
Works fine on master
julia> module FooMod
function define_ops(x)
for sym in (:pos, :pes)
@eval $(sym)(y) = y + $x
end
end
export define_ops
export pos, pes
end
Main.FooMod
julia> using .FooMod
julia> define_ops(2)
julia> pos(1)
3
julia> pos(2)
4
julia> pes(2)
4