Skip to content

Instantly share code, notes, and snippets.

@lukeburns
Created April 4, 2021 02:23
Show Gist options
  • Select an option

  • Save lukeburns/a895d77e5f9b0552acae82f4e6b58918 to your computer and use it in GitHub Desktop.

Select an option

Save lukeburns/a895d77e5f9b0552acae82f4e6b58918 to your computer and use it in GitHub Desktop.
Nodelike require in Julia (probably you shouldn't do this)
macro require(mod)
try
Base.require(__module__, Symbol(mod)) # like require("module")
catch e
mod = string(mod)
include(mod) # like require("./module.js")
end
end
macro assign(ex)
if string(ex.head) == "="
syms = string(ex.args[1])
for (a, b) in [("{", "("), ("}", ")"), ("(", ""), (")", "")]
syms = replace(syms, a => b)
end
syms = rstrip.(lstrip.(string.(syms)))
syms = filter(!isempty, syms)
object = ex.args[2]
for sym in syms
@eval $(Symbol(sym)) = try
getproperty($object, Symbol($(sym))) # structs, modules
catch e
try
if haskey($object, $sym)
get($object, $sym, nothing) # dicts
end
catch e
# allow for partial assignments, like { a, b } = { a: 0 }
end
end
end
end
end
# matrix.jl
A = [0 -1; 1 0]
# main.jl
A = @require("matrix.jl")
@require("Statistics").det(A)
@assign { tr } = @require(Statistics); tr(A) # equivalent to import Statistics: tr
@lukeburns

Copy link
Copy Markdown
Author

I wanted to be able to do:

@require(Pkg).activate()

instead of

import Pkg; Pkg.activate()

and without polluting the global namespace.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment